has_many_polymorphs中的冲突关联

时间:2011-01-20 11:58:03

标签: ruby-on-rails ruby-on-rails-3 polymorphism polymorphic-associations 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写了一个故事。现在@ user.stories.size = 1.然后@user收藏另一个故事。现在@ user.stories ...等一下。 @user has_many:stories and:has_many:story through: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

然后将故事和评论子类化为:

class FavoriteStory < Story
end

class FavoriteComment < Comment
end

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

但是当我在引用评论时出现此错误时:

ActiveRecord :: Associations :: UsersController中的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.

我在similar context中发现了对此错误的讨论,但它没有回答我的问题。

这里发生了什么?我怎样才能更好地做到这一点?

1 个答案:

答案 0 :(得分: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