views:

44

answers:

2

I'm having trouble with the Dynamic attribute-based finders in rails. They don't seem to exits for my model.

class Person < ActiveRecord::Base
  belongs_to :team
end

class Team < ActiveRecord::Base
  has_many :people
end

So in script/console, to find the teams having person with ID 1, I should be able to do:

>> Team.find_by_person_id(1)

I get the error:

NoMethodError: undefined method `find_by_person_id'

This is really odd because searching in the opposite direction, i.e:

>>Person.find_all_by_team_id(1)

Will successfully find all the people on team 1.

What needs to be done, to find the team by person_id?

+1  A: 

If you want to find a particular person among the people that belong to certain team, you would give:

@some_team.people.find_by_id(1)

Person.find_all_by_team_id works because team_id is a column in People table.

Team.find_by_person_id(1) doesn't work because:

1) Team is the class and not an instance of that class, which means that it doesn't have the people method and that is why you get the no_method_error, and

2) Even if get the instance part correctly (i.e. @some_team.people.find_by_person_id) a Person doesn't have a person_id column, but it has an id column instead. That's why I mentioned @some_team.people.find_by_id above.

Petros
That also returned: NoMethodError: undefined method `people'
SooDesuNe
Well, I just tried that on a fresh rails project and it works. There must be some other problem that you have that causes the error. Could you describe exactly what you are typing starting from the terminal until you get the error?
Petros
RAILS_ROOT/script/consoleThen copy and pasted your solution.rails v2.3.8">> Person#" shows "team_id" If I remove the has_many :people, I get the error: ArgumentError: No association found for name `people'. Has it been defined yet?I'm clueless here.
SooDesuNe
`Team.people` will not work. I'm sure you mean `@some_particular_team.people`.
hakunin
Yes you are right, I apologize. I was focused on the find_by_id part. I was even writing it correctly in script/console to test it, but having it wrong here. Brain can play weird tricks some times.
Petros
A: 

What you're trying to do is get a team when you know the person.

person = Person.find(1)
team = person.team

# or in one line
team = Person.find(1).team
hakunin