Rails find_by 宏与 has_many 关系

发布于 2024-09-10 03:00:01 字数 562 浏览 2 评论 0原文

我在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我们只是彼此的过ke 2024-09-17 03:00:01

如果您想在属于某个团队的人员中查找特定人员,您可以给出:

@some_team.people.find_by_id(1)

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:

@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.

后知后觉 2024-09-17 03:00:01

当你认识这个人时,你要做的就是组建一个团队。

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

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文