2012-09-29 2 views
1

레일스 어플리케이션에서 hstore 열에 범위를 만들려고합니다. 제품은 모델이며 기능은 hstore 유형의 속성입니다 (PostgreSQL 9.2 사용). 범위가 포함 된 클래스는 다음과 같이 정의됩니다.배열이나 매개 변수를 레일에서 hstore 범위로 전달할 때 오류가 발생했습니다.

class Product < ActiveRecord::Base 
    scope :with_features, lambda {|features| where("foo_id in (?)", features) 

위의 범위는 단일 값을 기능으로 전달한 경우에만 작동합니다. 배열에서 오류가 발생합니다. 이 아래에 예시되어있다 : 레일 3.2에서

Product.with_features('api') 
    => [#<Product id: 1, name: "Sample">] 
    # so great success 

# now with an array 
Product.with_features(['api','mobile']) 
    => ActiveRecord::StatementInvalid: PG::Error: ERROR: argument of WHERE must be type boolean, not type record 
    # so no good, this query will work as usual if features isn't of type hstore 

, 배열이 (내가 https://github.com/softa/activerecord-postgres-hstore을 사용하고 있습니다) 참여하는 경우 포스트 그레스의 hstore 유형에 대한 지원이 제한되어 보인다. 나는 각각의 루프를 사용하여 몇 가지 솔루션을 시도해 왔으며 많은 쿼리를 추가했다. 어떤 아이디어?

답변

0

여기에 내가 그와 함께 하나 개의 솔루션은 잘 작동의 :

scope :with_features, lambda { |features| 

    #store the composed scope in local variable to build on 
    composed_scope = self.scoped 

    # if array, then loop through each 
    if features.instance_of?(Array) 
    features.each do |feature| 
     composed_scope = composed_scope.where("features ? :key", :key => feature) 
    end 

    # otherwise, it's a single string parameter, parse as normal 
    else 
    composed_scope = composed_scope.where("features ? :key", :key => features) 
    end 

    # return the newly built composed scope 
    composed_scope 
} 

을 이제 모두 예를 들어 쿼리 수익 예상 결과보다.

관련 문제