2013-09-27 5 views
0

내가 인수에 내 Post 모델의 다형성 연관을 사용하고 여기에다형성 has_one 연관 속성을 사용하여 쿼리하는 방법은 무엇입니까?

내 모델입니다,

class Post < ActiveRecord::Base 
    belongs_to :post_module, polymorphic: true 
end 

class Album < ActiveRecord::Base 
    has_one :post, as: :post_module 
    belongs_to :artist 
end 

class Artist < ActiveRecord::Base 
    has_many :albums 
end 

지금 나는이 (공통 게시물을 가지고, 신체, 날짜, 등 ... 제목 속성) 지금은 그 POS의 같은 아티스트 ID로 앨범의 모델을 가지고 Post의를 조회하려는 Album 모델

@post = Post.find(params[:id]) #its :post_module is an Album model 

:post_module으로이 Post 모델 t의 앨범 아티스트 ID입니다.


내가 Post

@albums = Album.where('albums.artist_id = "?"', @post.post_module.artist.id) 
세트를 원하는 ... 그 @post의 앨범 같은 아티스트 ID로 Album 모델을 조회 할 수 있습니다 ...하지만 그건 내가 원하는 게 아니에요

어떻게하면됩니까? 또는 나는 나쁜 모델 관계를 설계하고 있는가? 예술가

artist = Artist.last 

#This will get a scoped object for all posts belonging to this artist's albums 
posts = Post.where(id: artist.albums) 
모델 디자인에 대한

,이 개 제안에 대한

답변

0

나는 나가서 설명하자면 NameError에 오류가 작동하지 않습니다

Post.joins('LEFT OUTER JOIN albums ON albums.id = posts.post_module_id').where('posts.post_module_type = "Album" AND albums.artist_id = "?"', @artist.id)

0

게시물 : 유일한 앨범이 후, 필요 없음의 다형성과 연관됩니다

  1. , 내가 추측하지만 당신은 더있을 수 있습니다. 다형성 이름
  2. 이 대회는, 형용사를 사용 postable 대신 내가 제대로 이해하면
0

post_module의 것입니다, 당신은 주어진 아티스트 ID에 대한 모든 게시물을 검색 할 수 있습니다. 그래서 :

@posts = Post.joins(:post_module => :album).where(:post_module => { :album => { :artist_id => artist_id }}) 
+0

으로 돌아가 셨습니다 : 초기화되지 않은 상수 포스트 :: PostModule – synthresin