我有3个模型:User,Object,Like
目前,我有一个模型:一个用户有很多对象。如何进行建模:
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
最佳答案
为了进一步阐述我对Brandon Tilley的回答的评论,我提出以下建议:
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
关于ruby-on-rails - 如何在Rails中建模 "Likes"?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11945487/