Rails 孙子对象带有 :has_many, :through
我的模式结构如下:
class Foo < ActiveRecord::Base
has_many :foo_bars
has_many :foo_bar_bazs, :through => :foo_bars
end
class FooBar < ActiveRecord::Base
has_many :foo_bars
belongs_to :foo_bar
end
Class FooBarBaz < ActiveRecord::Base
belongs_to :foo_bar
end
我正在尝试对 Foo 模型进行选择 - 例如 Foo.find(:all)。 FooBar 和 FooBarBaz 在数据库中都有正确的外键列(分别为 foo_id 和 foo_bar_id)。那么当我访问祖父母对象(Foo)时,如何访问子对象和孙对象呢?
最后,我需要在三个嵌套循环中迭代 Foo 对象,然后遍历 Foobar 对象,然后遍历 FoobarBaz 对象。
I have a schema structured as follows:
class Foo < ActiveRecord::Base
has_many :foo_bars
has_many :foo_bar_bazs, :through => :foo_bars
end
class FooBar < ActiveRecord::Base
has_many :foo_bars
belongs_to :foo_bar
end
Class FooBarBaz < ActiveRecord::Base
belongs_to :foo_bar
end
I'm trying to do a select on the Foo model - like Foo.find(:all). Both FooBar and FooBarBaz have the correct foreign key column in the database (foo_id and foo_bar_id, respectively). So how do I access the child and grandchild objects when I access the grandparent object (Foo)?
In the end I need to be iterate through the Foo objects, then through the Foobar objects, then through the FoobarBaz objects, in three nested loops.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,我将修改语法以匹配约定:
现在我们有了对象:
现在,可以避免 :through,并且您可以执行以下操作:
获取所有子项:
获取所有孙子项:
First, I'd revise the syntax to match convention:
Now that we have the objects:
Now, :through can be avoided, and you can do:
To get all children:
To get all grandchildren:
你不应该使用驼峰命名法来命名你的关联,而应该使用蛇形命名法:
You shouldn't use camel case to name your associations, but snake case:
我认为您的 FooBar 模型有错误。我认为你想说它属于 Foo,而不是 FooBar (目前你有 FooBar 属于它自己)。
假设您已准备好所有其他数据和关系,您应该可以将其称为 foo.foo_bar
I think there is a mistake on your FooBar model. I think you intended to say that it belongs_to Foo, not FooBar (currently you have FooBar belong to itself).
Assuming you have all the other data and relationship in place, you should be able to call it foo.foo_bar