【问题标题】:Rails grandchildren objects with :has_many, :throughRails 孙对象具有 :has_many, :through
【发布时间】:2023-03-23 17:56:01
【问题描述】:

我的架构结构如下:

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 对象。

【问题讨论】:

    标签: ruby-on-rails rails-activerecord


    【解决方案1】:

    首先,我会修改语法以匹配约定:

    class Foo < ActiveRecord::Base
      has_many :foo_bars
      has_many :foo_bar_bazs, :through => :foo_bars
    end
    
    
    class FooBar < ActiveRecord::Base
      has_many :foo_bar_bazs
      belongs_to :foo_bar
    end
    
    Class FooBarBaz < ActiveRecord::Base
      belongs_to :pc_scene_item
    end
    

    现在我们有了对象:

    Foo.find(:all, :include => [:foo_bars, :foo_bar_bazs])
    

    现在, :through 可以避免,您可以这样做:

    foos = Foo.find(:all, :include => [{:foo_bars => [:foo_bar_bazs]}])
    

    获取所有孩子:

    children = foos.collect{|f| f.foo_bars}.flatten.uniq
    

    要得到所有的孙子:

    grandchildren = foos.collect{|f| f.foo_bars.collect{|b| b.foo_bar_bazs}}.flatten.uniq
    

    【讨论】:

    • 当我尝试这个:Foo.find(:all, :include =&gt; [:foo_bars, :foo_bar_bazs]) 或这个:foos = Foo.find(:all, :include =&gt; [{:foo_bars =&gt; [:foo_bar_bazs]}]) 时,我得到一个“找不到名为 'foo_bar_bazs' 的关联,也许你拼错了它”错误......
    • 代码抱怨关联 has_many :foo_bar_bazs 不在 FooBar 类中。请仔细检查您的型号。
    • 啊,我明白了!模型中的错字。非常感谢,我星期五一整天都挂了电话。
    • @ssnkl 如果它解决了您的问题,接受答案是一种很好的形式;-)
    【解决方案2】:

    您不应该使用驼峰式命名您的关联,而应该使用蛇形命名:

    class Foo < ActiveRecord::Base
      has_many :foo_bars
      has_many :foo_bar_bazs, :through => :foo_bars
    end
    
    class FooBar < ActiveRecord::Base
      has_many :foo_bar_bazs
      belongs_to :foo
    end
    
    class FooBarBaz < ActiveRecord::Base
      belongs_to :foo_bar
    end
    

    【讨论】:

    • 没关系,在你回复之前我已经修好了。剩下的唯一问题是如何访问孙对象。
    【解决方案3】:

    我认为您的 FooBar 模型存在错误。我想你的意思是它属于 Foo,而不是 FooBar(目前你有 FooBar 属于它自己)。

    假设您拥有所有其他数据和关系,您应该可以将其称为 foo.foo_bar

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-04
      • 2014-09-01
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多