开发者

Rails find_by macros with a has_many relationship

开发者 https://www.devze.com 2023-01-07 18:48 出处:网络
I\'m having trouble with the Dynamic attribute-based finders in rails.They don\'t seem to exits for my model.

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:

>&g开发者_开发知识库t;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?


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号