2010-10-21 46 views
4

我正在尋找關於如何最好地爲我目前正在處理的應用程序構建「監視列表」的建議。實現「監視列表」關係的Rails/ActiveRecord

型號如下:

# user.rb 
has_many :items 

# item.rb 
belongs_to :user 

我現在需要增加一個觀察列表,用戶可以在喜歡的某些項目,沒有取得所有權。

我已經試過如下:

# 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 => :watches # as => :watchers 

這個排序的作品,但並沒有完全得到預期的迴應。我遇到了一個AssosciationTypeMismatch: Watch expected, got Item錯誤,這讓我覺得我的模型設置錯了。

理想情況下,我希望能夠像user.watches << item一樣開始觀看項目,item.watchers可以檢索觀看該項目的人員集合。

任何人都可以在這裏提供一些建議嗎?

回答

3

你必須定義:

# 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 

# watch.rb 
belongs_to :watcher, :class_name => 'User', :foreign_key => "user_id" 
belongs_to :watched_item, :class_name => 'Item', :foreign_key => "item_id" 

到能夠調用item.watchersuser.watched_items << item

+0

完美。謝謝! – Jeriko 2010-10-21 15:57:04

+0

這很有幫助,謝謝! – Levin 2014-12-17 14:46:38