我有 3 个模型:用户、对象、喜欢
目前,我有这样的模型:一个用户有很多对象。我该如何进行建模:
1)一个用户可以喜欢很多对象
2)一个对象可以有很多喜欢(来自不同的用户)
所以我希望能够做这样的事情:
User.likes = 用户喜欢的对象列表
Objects.liked_by = 对象喜欢的用户列表
下面的模型肯定是错误的......
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
为了进一步阐述我对布兰登·蒂利的回答的评论,我建议如下:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)