簡體   English   中英

在導軌HABTM與HM / BT中模擬“喜歡”

[英]Modeling “Likes” in rails HABTM vs HM/BT

為我的應用在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

哪種方法最好,為什么? 我還計划在我的應用程序中添加一個活動供稿,以幫助確定最佳方法。

這個問題的答案取決於Like是否會具有任何屬性或方法。

如果其唯一存在的目的是作為UserThing之間的has_and_belongs_to_many關系,則使用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因為它們是多余的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM