Rails find_by 宏与 has_many 关系
我在使用 Rails 中基于动态属性的查找器时遇到问题。他们似乎不适合我的模型。
class Person < ActiveRecord::Base
belongs_to :team
end
class Team < ActiveRecord::Base
has_many :people
end
因此,在脚本/控制台中,要找到 ID 为 1 的人员的团队,我应该能够执行以下操作:
>> Team.find_by_person_id(1)
我收到错误:
NoMethodError: undefined method `find_by_person_id'
这真的很奇怪,因为朝相反方向搜索,即:
>>Person.find_all_by_team_id(1)
将成功找到团队 1 中的所有人员 ?
需要做什么才能通过 person_id
找到团队
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想在属于某个团队的人员中查找特定人员,您可以给出:
Person.find_all_by_team_id 有效,因为 team_id 是人员表中的一列。
Team.find_by_person_id(1) 不起作用,因为:
1)Team 是类,而不是该类的实例,这意味着它没有 people 方法,这就是您收到 no_method_error 的原因,
2)甚至如果正确获取实例部分(即@some_team.people.find_by_person_id),则 Person 没有 person_id 列,但它有 id 列。这就是为什么我在上面提到@some_team.people.find_by_id。
If you want to find a particular person among the people that belong to certain team, you would give:
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.