【问题标题】:Rails get nested attribute based in has_many relationRails 获取基于 has_many 关系的嵌套属性
【发布时间】:2016-06-24 21:21:52
【问题描述】:

我有 3 节课

Class User < ActiveRecord::Base

 has_many :dogs

end

Class Dog < ActiveRecord::Base

 belongs_to :user
 has_many :tags

end

class Tag < ActiveRecord::Base
  belongs_to :dog
end

我尝试执行 User.dogs 并得到一个 Dog 实体列表,如下所示:

[Dog, Dog, Dog, Dog]

如果我访问数组中的 Dog 实体,我将获得 Dog 的所有属性并且工作正常。但我的问题是我需要在 Dog 中包含 Tag 实体。

例如,如果我这样做

user.dogs.each do |dog_entity|
   puts dog_entity.tags #Prints the tags related value of Tag in Dog.
 end

当我执行User.dogs 时,如何将与 Dog 相关的 Tag 值放入数组中的每个 Dog 中?

【问题讨论】:

    标签: ruby-on-rails ruby rails-activerecord has-many


    【解决方案1】:

    dogs 是关联,所以你应该在对象而不是模型上调用它。

    我认为这应该可行

    user.dogs.includes(:tags).each do |dog|
      puts dog.tags
    end
    

    注意user 是对象而不是模型。
    includes(:tags) 允许我们避免 n+1 问题。

    另请注意,模型名称应为单数,即Dog 而不是Dogs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多