Rails / ActiveRecord implementing a "Watch list" relationship
I'm looking for advice on how best to construct a "watch-list" for the app I'm currently working on.
Models as follows:
# user.rb
has_many :items
# item.rb
belongs_to :user
I need to now add a watch-list, where users can favorite certain items, without taking ownership.
I've tried the following:
# user.rb
has_many :items
has_many :watches
has_many :items, :through => :watches
# watch.rb (user_id:integer, item_id:integer)
belongs_to :user
belongs_to :item
# item.rb (user_id:integer)
belongs_to :user
has_many :watches
has_many :users, :through => :w开发者_JAVA百科atches # as => :watchers
This sort-of works, but doesn't quite give the desired response. I'm getting an AssosciationTypeMismatch: Watch expected, got Item
error, among others, which makes me think I've got the models set up wrong.
Ideally, I'd like to be able to do things like user.watches << item
to start watching an item, and item.watchers
to retrieve a collection of people watching the item.
Can anyone offer some suggestions here?
You have to define:
# user.rb
has_many :items
has_many :watches
has_many :watched_items, :through => :watches
# item.rb
belongs_to :user
has_many :watches
has_many :watchers, :through => :watches
and
# watch.rb
belongs_to :watcher, :class_name => 'User', :foreign_key => "user_id"
belongs_to :watched_item, :class_name => 'Item', :foreign_key => "item_id"
to be able to call item.watchers
and user.watched_items << item
精彩评论