Ruby on rails RubyonRails:列出的产品属于/有很多关联

Ruby on rails RubyonRails:列出的产品属于/有很多关联,ruby-on-rails,has-many,belongs-to,Ruby On Rails,Has Many,Belongs To,我正在尝试用用户、房间和产品构建RoR应用程序。 我将在下面列出我的模型 class Product < ActiveRecord::Base belongs_to :user validates :name, :user_id, presence: true validates :price, numericality: { greater_than_or_equal_to: 0 }, presence: true end class User < ActiveRecord

我正在尝试用用户、房间和产品构建RoR应用程序。 我将在下面列出我的模型

class Product < ActiveRecord::Base
 belongs_to :user
 validates :name, :user_id, presence: true
 validates :price, numericality: { greater_than_or_equal_to: 0 }, presence: true
end

class User < ActiveRecord::Base
 has_many :products, dependent: :destroy
 has_many :memberships, dependent: :destroy
 has_many :rooms, through: :memberships
 <...>
end

class Room < ActiveRecord::Base
 has_many :memberships
 has_many :users, through: :memberships
 validates :name, presence: true, length: { in: 6..20 }
end

class Membership < ActiveRecord::Base
 belongs_to :user
 belongs_to :room
 validates :user_id, presence: true
 validates :room_id, presence: true
end
类产品
用户可以拥有许多产品,他们可以加入/离开房间

I我的视图我想显示当前_用户的房间(其中有多个拥有多个产品的用户),并按该房间中的所有用户列出所有产品(并按DESC中创建的_排序)。你能帮我找到一个好方法来实现这一点吗


提前谢谢

您可以使用eager\u load加载模型关联。这是一个很好的开始,可以了解快速加载、include和join及其差异

现在,您可以对用例使用以下查询

result = current_user.eager_load(:rooms => [:users => :products ]).order("rooms.created_at DESC")

希望这有帮助。

欢迎来到stackoverflow。网上有100个教程展示了如何做到这一点,请查阅其中一个,如果你有一个具体的问题,欢迎你在这里发布。这似乎是我一直在寻找的。谢谢你的建议。我现在正在寻找渴望的负载。我很高兴它为你工作,请接受这个答案。