[英]Modeling “Likes” in rails HABTM vs HM/BT
What would be the best method to model "likes" in rails for my app. 为我的应用在rails中建模“喜欢”的最佳方法是什么。 I could either to the following:
我可以执行以下操作之一:
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
Or 要么
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
What approach would be best and why? 哪种方法最好,为什么? I plan to have an activity feed in my app as well, if that helps determine the best approach.
我还计划在我的应用程序中添加一个活动供稿,以帮助确定最佳方法。
The answer to this question depends on whether or not Like
will ever have any attributes or methods. 这个问题的答案取决于
Like
是否会具有任何属性或方法。
If its only purpose of existence is to be the HABTM relationship between User
s and Thing
s, then using the has_and_belongs_to_many
relationship would suffice. 如果其唯一存在的目的是作为
User
和Thing
之间的has_and_belongs_to_many
关系,则使用has_and_belongs_to_many
关系就足够了。 In your example, having has_many
and belongs_to
is redundant. 在您的示例中,
has_many
和belongs_to
是多余的。 All you would need in this case is: 在这种情况下,您需要做的只是:
class User < ActiveRecord::Base
has_and_belongs_to_many :things
end
class Thing < ActiveRecord::Base
has_and_belongs_to_many :users
end
On the other hand, if you anticipate that a Like
will have an attribute (eg maybe someone will really like something, or love it, etc.) then you can do 另一方面,如果您预计“
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
Note that I removed has_many :things
and belongs_to :user
as they are redundant. 请注意,我删除了
has_many :things
和belongs_to :user
因为它们是多余的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.