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
次に、ストーリーとコメントを次のようにサブクラス化します。
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.
同様のコンテキストでこのエラーに関する議論を見つけましたが、私の質問には答えません。
何が起きてる?どうすればこれを改善できますか?