【发布时间】:2011-06-12 10:06:55
【问题描述】:
我正在使用 has_many_polymorphs 在多个用户可以发布故事和制作 cmets 的网站上创建“收藏夹”功能。我希望用户能够“喜欢”故事和 cmets。
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 写了一个故事。现在@user.stories.size = 1。然后@user 收藏了一个不同的故事。现在@user.stories... 等一下。 @user has_many :stories 和 :has_many :stories 到 :favorites。
当我尝试调用@user.stories 或@user.cmets 时出现问题。我想为他们拥有的故事调用@user.stories,为他们喜欢的故事调用@user.favorites.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。
但是当我在引用 cmets 时收到此错误:
ActiveRecord::Associations::PolymorphicError in UsersController#show
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 中发现了有关此错误的讨论,但它没有回答我的问题。
这里发生了什么?我怎样才能做得更好?
【问题讨论】:
-
我在这里遇到了同样的问题:stackoverflow.com/questions/5768764/… 你最后做了什么?
标签: ruby-on-rails ruby-on-rails-3 polymorphism polymorphic-associations has-many-polymorphs