3

저는 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 및 : has_many : stories through : 즐겨 찾기.

@ 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 

을 다음 이야기를 서브 클래스 등과 같은 코멘트 : 나는 user.stories @ 및 user.favorite_stories @ 호출 할 수 있습니다 해주기 때문에 문제를 해결

class FavoriteStory < Story 
end 

class FavoriteComment < Comment 
end 

.

하지만 나는 의견을 참조하여이 오류가 발생하는 경우 : #이

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에서이 오류의 논의를보기

액티브 :: 협회 :: PolymorphicError UsersController에 ,하지만 내 질문에 대답하지 않습니다.

여기 무슨 일 이니? 어떻게하면 더 잘 할 수 있을까요?

+0

내가 여기에 같은 문제에 봉착 : http://stackoverflow.com/questions/5768764/how-to-set-up-these-crud-controller-actions-for-has-many-polymorphs -and-an-error 무엇을 끝내셨습니까? –

답변

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 
+0

테스트하지 않았지만 제대로 작동하는지 확인했습니다. – Galen