Search code examples
ruby-on-railsdynamic-finders

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?


Solution

  • 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