1

다음을 변환하는 방법을 알고있다. Arel 메소드를 혼합 된 sql/string 대신 사용하는 방법을 알고 있지만, 결과 arel 객체를 ActiveRecord :: Relation에 병합하는 방법을 알고있다. 따라서 더 많은 AR :: 관계 메소드를 연결할 수있다. 그 위에. arel 객체를 ActiveRecord :: Relation 체인에 병합하는 방법은 무엇입니까?

내가 가지고 내 앞의 질문에 다음과 같은 매우 도움이 대답 : 내가 arel 객체에 결국 나는 '돈

class Address < ActiveRecord::Base 
    scope :anywhere, lambda{|search| 
    addr_arel = Address.arel_table 
    attrs = [:line1, :line2, :city, :state, :zip] 
    attrs.inject {|attr| 
     q = addr_arel[attr].match("%#{search}%") unless q 
     q = q.or(addr_arel[attr].match("%#{search}%") 
    } 
    } 
end 

그러나 : 나는 이런 식으로 뭔가를하려고 노력

class Address < ActiveRecord::Base 
    scope :anywhere, lambda{|search| 
    attrs = [:line1, :line2, :city, :state, :zip] 
    where(attrs.map{|attr| 
     "addresses.#{attr} LIKE :search" 
    }.join(' OR '), search: "#{search}%").order(*attrs) 
    } 
end 

Person.joins(:address).merge(Address.anywhere(query_term)) 

다음 ActiveRecord와 병합하는 방법을 알고 :: 관계 :

Person.joins (: 주소) .merge (Address.anywhere (query_term))

(주사는 매우 우아하지 않습니다. - 어떻게 향상시킬 수 있습니까?)

답변

2

ActiveRecord :: Relation.where는 ARel 술어를 허용하므로이 경우에는 최종 조건자를 직접 Address.where.

class Address < ActiveRecord::Base 
    scope :anywhere, -> search { 
    addr_arel = Address.arel_table 
    attrs = [:line1, :line2, :city, :state, :zip] 

    where attrs 
     .map {|attr| addr_arel[attr].matches("%#{search}%")} 
     .inject(:or) 
    } 
end