3

I'm using has_many_polymorphs to create a "Favorites" feature on a site where multiple users can post stories and make comments. I want users to be able to "favorite" stories and comments.

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

Now say @user writes a story. Now @user.stories.size = 1. Then @user favorites a different story. Now @user.stories... wait a minute. @user has_many :stories and :has_many :stories through :favorites.

The issue arises when I attempt to call @user.stories or @user.comments. I want to call @user.stories for stories they own and @user.favorites.stories for stories they favorite.

So I tried this:

class User < ActiveRecord::Base
 has_many :stories
 has_many :comments

 has_many_polymorphs :favorites, :from => [:favorite_stories, :favorite_comments]
end

and then subclassed Story and Comment like so:

class FavoriteStory < Story
end

class FavoriteComment < Comment
end

That fixed the problem because now I can call @user.stories and @user.favorite_stories.

BUT when I get this error in reference to comments:

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.

I found discussion of this error in a similar context, but it doesn't answer my question.

What's going on here? How can I do this better?

Galen
  • 636
  • 6
  • 12
  • I'm having the same problem here: http://stackoverflow.com/questions/5768764/how-to-set-up-these-crud-controller-actions-for-has-many-polymorphs-and-an-error what did you end up doing? – Justin Meltzer Apr 24 '11 at 20:48

1 Answers1

0

What about something like this?

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
iHiD
  • 2,450
  • 20
  • 32