2015-11-01 63 views
1

这里是我的模型:Rails的ActiveRecord的深层渴望装载

class User < ActiveRecord::Base 
    has_many :products 
    has_many :comments 
end 

class Product < ActiveRecord::Base 
    belongs_to :user 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :product 
end 

我需要从当前用户得到评论记录产品只有

我如何去做?感谢

回答

2

假如我们把关系到使用has_many: comments, through: products你也许可以得到你以后:

class User < ActiveRecord::Base 
    has_many :products 
    has_many :comments, through: products 
end 

class Product < ActiveRecord::Base 
    belongs_to :user 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :product 
end 

现在你可以做user.comments

轨道文档是here,其中说:

一个的has_many:通过协会经常被用来建立与其他模型中的许多一对多 连接。该关联表明,通过继续执行第三个模型,可以将声明模型与另一个 模型的零个或多个实例进行匹配。例如,考虑一个 医疗实践,病人预约看医生。

+0

非常感谢:D –