3

我正在使用 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 写了一个故事。现在@user.stories.size = 1。然后@user 收藏了一个不同的故事。现在@user.stories... 等一下。@user has_many :stories 和 :has_many :stories 到 :favorites。

当我尝试调用@user.stories 或@user.comments 时出现问题。我想为他们拥有的故事调用@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

然后像这样子类化 Story 和 Comment:

class FavoriteStory < Story
end

class FavoriteComment < Comment
end

这解决了问题,因为现在我可以调用@user.stories 和@user.favorite_stories。

但是当我在参考评论时收到此错误时:

用户控制器中的 ActiveRecord::Associations::PolymorphicError#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.

我在类似的上下文中发现了对这个错误的讨论,但它没有回答我的问题。

这里发生了什么?我怎样才能做得更好?

4

1 回答 1

0

这样的事情呢?

class UserFavorite < ActiveRecord::Base
  belongs_to :user
  belongs_to :favorite, :polymorphic => true
end

class User < ActiveRecord::Base
  has_many :favourite_story_items, :class_name => "UserFavourite", :conditions => "type = 'Story'"
  has_many :favourite_stories, :through => :favourite_story_items, :as => :favourite
  has_many :favourite_comment_items, :class_name => "UserFavourite", :conditions => "type = 'Comment'"
  has_many :favourite_comments, :through => :favourite_comment_items, :as => :favourite
end
于 2012-05-26T01:41:09.840 回答