我正在使用has_many_polymorphs在網站上創建一個「收藏夾」功能,多個用戶可以發佈故事並發表評論。我希望用戶能夠「喜歡」故事和評論。has_many_polymorphs中的衝突關聯
class User < ActiveRecord::Base
has_many :stories
has_many :comments
has_many_polymorphs :favorites, :from => [:stories, :comments]
end
class Story < ActiveRecord::Base
belongs_to :user, :counter_cache => true
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :user, :counter_cache => true
belongs_to :story, :counter_cache => true
end
class FavoritesUser < ActiveRecord::Base
belongs_to :user
belongs_to :favorite, :polymorphic => true
end
現在說@user寫一個故事。 Now @ user.stories.size = 1.然後@user收藏一個不同的故事。 Now @ user.stories ...等一下。 @user has_many:故事和:has_many:故事通過:收藏夾。
當我嘗試呼叫@ user.stories或@ user.comments時,就會出現此問題。我想爲他們擁有的故事和@ user.favorites.stories調用@ user.stories來獲取他們最喜歡的故事。
所以,我想這一點:
class User < ActiveRecord::Base
has_many :stories
has_many :comments
has_many_polymorphs :favorites, :from => [:favorite_stories, :favorite_comments]
end
,然後子類的故事和評論,像這樣:
class FavoriteStory < Story
end
class FavoriteComment < Comment
end
這解決了這一問題,因爲現在我可以叫@ user.stories和@ user.favorite_stories 。
但,當我得到這個錯誤參考意見:
的ActiveRecord ::協會:: PolymorphicError在UsersController#顯示
Could not find a valid class for :favorite_comments (tried FavoriteComment). If it's namespaced, be sure to specify it as :"module/favorite_comments" instead.
我發現這個錯誤的討論在similar context ,但它不回答我的問題。
這是怎麼回事?我怎樣才能做得更好?
我在這裏有同樣的問題:http://stackoverflow.com/questions/5768764/how-to-set-up-these-crud-controller-actions-for-has-many-polymorphs - 錯誤你最終做了什麼? – 2011-04-24 20:48:31