Conflicting associations in has_many_polymorphs

I use 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 that @user is writing a story. Now @ user.stories.size = 1. Then, the @user favorite is another story. Now @ user.stories ... wait a minute. @user has_many: stories and: has_many: stories via: favorites.

The problem occurs when I try to call @ user.stories or @ user.comments. I want to call @ user.stories for my stories and @ user.favorites.stories for my favorite stories.

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 subclasses of Story and Comment:

class FavoriteStory < Story
end

class FavoriteComment < Comment
end

, @user.stories @user.favorite_stories.

, :

ActiveRecord:: :: PolymorphicError UsersController # show

Could not find a valid class for :favorite_comments (tried FavoriteComment). If it namespaced, be sure to specify it as :"module/favorite_comments" instead.

, .

? ?

+3
1

?

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
0

Source: https://habr.com/ru/post/1786653/


All Articles