3

나는이 세 가지 다른 테이블의 다형성 연관이 하나 개의 모델 : 당신이 볼 수 있듯이가져 오는 행

class User < ActiveRecord::Base 
    belongs_to :authenticatable, :polymorphic => true 


# == Schema Information 
# 
# Table name: employees 
# 
# id      :integer(4)  not null, primary key 
# ... 
# school_id    :integer(4) 

class Guardian < ActiveRecord::Base 
    has_one :user, :as => :authenticatable 
    belongs_to :school 


# == Schema Information 
# 
# Table name: guardians 
# 
# id      :integer(4)  not null, primary key 
# ... 
# school_id    :integer(4) 

class Guardian < ActiveRecord::Base 
    has_one :user, :as => :authenticatable 
    belongs_to :school 

# == Schema Information 
# 
# Table name: students 
# 
# id      :integer(4)  not null, primary key 
# ... 
# school_id    :integer(4) 

class Student < ActiveRecord::Base 
    has_one :user, :as => :authenticatable 
    belongs_to :school 

는 지난 3 개 모델은 "학교"모델에 속하고, 따라서를 school_id이라는 열이 있어야합니다. 나는 user에서 모든 해당 행을 검색하여 해당 인증 가능한 school_id가 어떤 값과 같도록하려고합니다. 명확히하기 위해, 나는 같은 것을 할 싶습니다

User.joins(:authenticatable).where(:school_id => some_value) 

을 그대로, 즉 마지막 주에

ActiveRecord::EagerLoadPolymorphicError 

가 발생합니다, 내가 제안 몇 가지 문서를 찾기 위해 관리 그 다형성 연관이 같은 작업을해야에 포함하여 :

: 나는이 작업을 수행 할 경우

User.find(:all, :include => :authenticatable) (This works) 

User.find(...)Array을 반환하고 해당 클래스에 where 메서드가 정의되어 있지 않기 때문에 레일이 끊어집니다.

다른 옵션을 시도했지만 원하는 것을 성취 할 수있는 방법을 찾지 못했습니다. 너 나 좀 도와 줄 수있어? 감사!

+0

http://exackoverflow.com/questions/2079867/activerecordeagerloadpolymorphicerror-can-not-eagerly-load-the-polymorphic-ass – mark

답변

1

당신은 joins 문에 SQL 쿼리를 사용하여 그것을 해결하기 위해 시도 할 수 있습니다 :

Model1.joins("INNER JOIN model2 ON model2.id = model1.polymorphizm_id INNER JOIN model3 ON model3.id = model1.polymorphizm_id INNER JOIN model4 ON model4.id = model1.polymorphizm_id").where("model2.column_id = ... or model3.column_id = ... or model4.column_id = ...") 

내가 실제로 그것을 시도하지만, polimorphic ASSOC 없습니다. 모델에 두 개의 열을 추가합니다 (xxx_typexxx_id). 그들은 assoc을 처리하는 역할을합니다. 여러 모델로.

+0

답장을 보내 주셔서 감사합니다. 네가 제안한 것은 효과가 없었다. 그것은 나에게 어떤 행도 돌려 줬다. 더 이해할 수 있도록 내 질문을 업데이트했습니다. – sauronnikko

+0

그래서 귀하의 게시물을 읽었습니다. 시도해 보셨습니까? : User.include (: authenticatable) .where (: school_id => some_value)'this는 ActiveRelation 객체를 반환해야하고,'.all'을 호출 할 수 있습니다. 'NoMethodError : private 메소드 'include'가 #에 대해 호출되었습니다. some_value)'도움을 받았다면 – bor1s

+0

도와주세요. 0x00000106c2a5b8>' '포함'(복수)을 시도했습니다. 그것은 말했다 : 'Mysql2 :: 오류 : 'where 절'에서 알 수없는 열 'users.school_id': ... ' – sauronnikko

0

당신은 하위 쿼리 주변 futz에 아마 뭔가 작업 얻을 수 있습니다 : 당신이 레일 (5)를 사용하는 경우 당신이 함께 일부에 가입하고자 할 수 있습니다 있도록

User.where(authenticable: Guardian.where(school_id: some_value)) 

, 그들은, ActiveRecord.or 추가를 :

User.all.merge(Guardian.where(school_id: some_value)) 
:
User.where(authenticable: Guardian.where(school_id: some_value)) 
    .or.where(authenticable: Student.where(school_id: some_value)) 

merge

어떤 결과를 얻을 수있는 또 다른 방법이다

다형성 테이블에 대한 쿼리에 너무 익숙하지 않아 위와 같이 마일리지가 다를 수 있습니다.

user_ids = Guardian.joins(:user).select('users.id').where(school_id: some_value).pluck(:user_id) + 
      Student.joins(:user).select('users.id').where(school_id: some_value).pluck(:user_id) 
users = User.where(id: user_ids) 

이제 스키마와 함께 붙어있을 수 있지만, 당신이 그것을 변경하는 자유에 있다면, 당신과 같은 : 최악의 경우, 당신은 범위를 유지하기 위해 둘 이상의 조회를 할 필요 끝낼 수 있습니다

class User < ActiveRecord::Base 
    belongs_to :school 
end 

class Student < User 
end 

class Guardian < User 
end 

그런 다음 당신은 단순히 말 : 나는 그들이 때문에 많은 경우에 가치가보다 더 문제가 될 다형성 관계를 발견했습니다

User.where(school_id: some_value) 

단일 테이블 상속 관계에 더 좋을 수도 있습니다 방법에 쿼리 및 대량 업데이트와 같은 작업을 수행하는 것은 물론 외래 키 제약 조건을 사용할 수 없도록 만드는 것이 어렵습니다. 몇 가지 추가 생각을하면, 일반적으로 합리적인 데이터 모델을 사용하면 문제없이 잘 작동합니다.

관련 문제