在rails HABTM vs HM / BT中建模“喜欢”

问题描述 投票:0回答:1

什么是为我的应用程序在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

什么方法最好,为什么?我计划在我的应用中提供活动Feed,如果这有助于确定最佳方法。

ruby-on-rails ruby activerecord social-networking
1个回答
2
投票

这个问题的答案取决于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,因为它们是多余的。

© www.soinside.com 2019 - 2024. All rights reserved.