2014-02-19 36 views
1

對象方向我們有這些模型的設置對於用戶來說,分類和收藏:選擇從最喜愛的模型

class Favorite < ActiveRecord::Base 
    belongs_to :favoritable, polymorphic: true 
    belongs_to :user, inverse_of: :favorites 
end 

class User < ActiveRecord::Base 
    has_many :favorites, inverse_of: :user 
end 

class Category < ActiveRecord::Base 
    has_many :favorites, as: :favoritable 
end 

也有可以收藏(子類別等)一些其他的對象,我想是能搶類別的對象,而不是直接的收藏夾列表:

@categories = @user.favorites.where(favoritable_type: "Category") 

有沒有辦法通過這個@user對象搶實際分類對象的列表?

+0

你有沒有發現這個http://stackoverflow.com/questions/21817019/rails-polymorphic-favorites-user-can-favorite-different-models – devanand

+0

呀,謝謝。這是我原來的問題,我將它作爲一個單獨的問題來使用。 – tmartin314

回答

1

您是否嘗試過在用戶中設置一個真實性?

class User < ActiveRecord::Base 
    has_many :favorites, inverse_of: :user 
    has_many :categories, through: :favorites 
end