2012-01-31 126 views
0

嗨我真的很陌生,我试图创建一个产品评级模型。导轨模型关系

因此,有用户(姓名,电子邮件,PW)

用户拥有的用户已评级的产品清单。评分(1-10)和评论。

每个产品都有自己的描述,评估他们的用户列表,评分和评论。

我该如何建立关系?我是否应该拥有3种型号,用户,评级,产品,还是只能通过用户和产品获得?

此外:has_many .etc关系会是什么样子?

回答

1

这会为has_many :through =>

用户模型有很大的情况下。

User has_many :ratings 
User has_many :products, :though => :ratings 

Rating Rating Model。

belongs_to :user 
belongs_to :product 

产品型号。

Product has_many :ratings 
Product has_many :users, :through => ratings 

n.b.这现在被认为优于has_and_belongs_to_many,许多人认为在这一点上基本上被弃用。
个人我从来没有喜欢使用has_many_and_belongs_to,因为它的工作原理,也因为频繁的重新工作将它变成has_many,通过一旦连接模型需要额外的属性(在这种情况下的评级) 。
其实你想要一个评级'水平',所以你已经有一个案例has_many, :through

3

这里就是我会做

class User 
    has_many :ratings 
    has_many :products, :through => :ratings 
end 

class Product 
    has_many :ratings 
    has_many :users, :through => :ratings 
end 

class Rating 
    belongs_to :user 
    belongs_to :product 
end 

这样,如果你想获得的所有评价一款产品的用户,你可以说product.users