【问题标题】:rails model relationship导轨模型关系
【发布时间】:2012-01-31 18:01:44
【问题描述】:

您好,我真的是 Rails 新手,我正在尝试创建产品评级模型。

所以有用户(姓名、电子邮件、密码)

Users 有一个用户评价过的产品列表。带有评分 (1-10) 和评论。

每个产品都有其描述、对其进行评分的用户列表、评分和评论。

我应该如何建立关系?我应该有 3 个模型,用户、评级、产品,还是我可以只使用用户和产品?

还有 :has_many .etc 的关系是什么样的?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    这就是我要做的事情

    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

    【讨论】:

      【解决方案2】:

      这对于has_many :through => 来说是一个很好的案例

      用户模型。

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

      评级模型。

      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 的案例!

      【讨论】:

        猜你喜欢
        • 2012-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多