您如何为“喜欢"模型建模?在铁轨上? [英] How do you model "Likes" in rails?
本文介绍了您如何为“喜欢"模型建模?在铁轨上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有3种模型:用户,对象,喜欢
I have 3 models: User, Object, Likes
当前,我有一个模型:一个用户有许多对象.我该如何建模:
Currently, I have the model: a user has many Objects. How do I go about modeling:
1)用户可以喜欢许多对象
1) A user can like many objects
2)一个对象可以有很多喜欢(来自不同的用户)
2) an Object can have many likes (from different users)
所以我希望能够做这样的事情:
So I want to be able to do something like this:
User.likes =用户喜欢的对象列表
User.likes = list of objects liked by a user
Objects.liked_by =对象喜欢的用户列表
Objects.liked_by = list of Users liked by object
下面的模型肯定是错误的...
The model below is definitely wrong...
class User < ActiveRecord::Base
has_many :objects
has_many :objects, :through => :likes
end
class Likes < ActiveRecord::Base
belongs_to :user
belongs_to :object
end
class Objects < ActiveRecord::Base
belongs_to :users
has_many :users, :through => :likes
end
推荐答案
要进一步阐述我对Brandon Tilley的回答的评论,我建议以下几点:
To elaborate further on my comment to Brandon Tilley's answer, I would suggest the following:
class User < ActiveRecord::Base
# your original association
has_many :things
# the like associations
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
# your original association
belongs_to :user
# the like associations
has_many :likes
has_many :liking_users, :through => :likes, :source => :user
end
这篇关于您如何为“喜欢"模型建模?在铁轨上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文