[英]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
是否會具有任何屬性或方法。
如果其唯一存在的目的是作為User
和Thing
之間的has_and_belongs_to_many
關系,則使用has_and_belongs_to_many
關系就足夠了。 在您的示例中, has_many
和belongs_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 :things
和belongs_to :user
因為它們是多余的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.