【问题标题】:Modeling "Likes" in rails HABTM vs HM/BT在 Rails HABTM 与 HM/BT 中建模“喜欢”
【发布时间】:2014-06-26 22:26:23
【问题描述】:

为我的应用程序在 Rails 中建模“喜欢”的最佳方法是什么。我可以:

class User < ActiveRecord::Base
  has_many :things

  has_many :likes
  has_many :liked_things, through: :likes, source: :thing
end

class Like < ActiveRecord::Base
  belongs_to :user
  belongs_to :thing
end

class Thing < ActiveRecord::Base
  belongs_to :user

  has_many :likes
  has_many :liking_users, through: :likes, source: :user
end

或者

class User < ActiveRecord::Base
  has_many :things

  has_and_belongs_to_many :things
end

class Thing < ActiveRecord::Base
  belongs_to :user

  has_and_belongs_to_many :users
end

哪种方法最好,为什么?如果这有助于确定最佳方法,我还计划在我的应用中添加活动源。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord social-networking


    【解决方案1】:

    这个问题的答案取决于Like 是否有任何属性或方法。

    如果其存在的唯一目的是成为Users 和Things 之间的HABTM 关系,那么使用has_and_belongs_to_many 关系就足够了。在您的示例中,拥有 has_manybelongs_to 是多余的。在这种情况下,您只需要:

    class User < ActiveRecord::Base
      has_and_belongs_to_many :things
    end
    
    class Thing < ActiveRecord::Base
      has_and_belongs_to_many :users
    end
    

    另一方面,如果您预计 Like 将有一个属性(例如,也许有人会真的喜欢某物,或喜欢它等),那么您可以这样做

    class User < ActiveRecord::Base
      has_many :likes
      has_many :liked_things, through: :likes, source: :thing
    end
    
    class Like < ActiveRecord::Base
      belongs_to :user
      belongs_to :thing
    end
    
    class Thing < ActiveRecord::Base
      has_many :likes
      has_many :liking_users, through: :likes, source: :user
    end
    

    请注意,我删除了 has_many :thingsbelongs_to :user,因为它们是多余的。

    【讨论】:

    • 谢谢马特。它实际上并不是多余的,它只是另一个关联,就像用户拥有东西或可以创建属于他的东西一样。
    • Like 可能出于其他原因有用,例如跟踪一个人喜欢某件事的日期,或仅出于查询目的(显示所有用户对某事物的最后 10 次喜欢等)。虽然这里可能不相关,但如果 Thing 是多态的,你可能不会使用 HABTM。
    • 是的,似乎加入模型是我想要的,只是为了让我的选择保持开放。
    • 加上 HABTM 实在是太恶心了。
    • @8vius 好的,这些肯定是有效的关联。然后考虑将它们删除以隔离手头的问题:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多