SooDesuNe
SooDesuNe

Reputation: 10030

Rails find_by macros with a has_many relationship

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?

Upvotes: 0

Views: 807

Answers (2)

Petros
Petros

Reputation: 8992

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.

Upvotes: 1

Max Chernyak
Max Chernyak

Reputation: 37357

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

Upvotes: 0

Related Questions