2010-05-05 3 views
0

레일 및 MySQL :MySQL/Rails에서 boolean 열이 true인지 확인

태그를 나타내는 여러 개의 부울 열이있는 테이블이 있습니다. 이 열 중 특정 것이 '참'(또는 MySQL의 경우 '1') 인 모든 행을 찾고 싶습니다. 내보기에 다음 코드가 있습니다.

@tag = params[:tag] 

@supplies = Supply.find(:all, 
    :conditions=>["? IS NOT NULL and ? !=''", @tag, @tag], :order=>'name') 

@tag는 url에서 전달됩니다. 그런데 왜 @tag에 대한 열에 해당하는 것이 아닌 모든 @supplies (즉, 모든 행)를 얻는 이유는 무엇입니까?

감사합니다. params[:tag]foo로 설정되어

답변

1

경우, find 방법은이 쿼리를 생성 : 두 조건이 항상 참이기 때문에이 모든 Supply 기록을 반환

select * from supplies where 'foo' is not null and 'foo' != '' order by name; 

.

    당신이 열 이름으로 params[:tag]에 대한하려는거야 물론
  1. 'foo' != ''

'foo' is not null

  • ,하지만 그건 단지 끔찍한 디자인입니다. 사용을 당신이 정말로 여러 태그에 대한 옵션을 가지고 공급하는 기능을 원하는 경우

    @supplies = Supply.all(:conditions => ["tag = ?", params[:tag]], :order => "name") 
    

    :

    당신은 당신의 Supply 모델에 tag 속성이 다음과 같은 파인더를 사용한다

    class Supply < ActiveRecord::Base 
        has_and_belongs_to_many :tags 
    end 
    
    class Tag < ActiveRecord::Base 
        has_and_belongs_to_many :supplies 
    end 
    
    @supplies = Supplies.all(:conditions => {:tags => ['foo', 'bar']}, :order => "name") 
    
  • +0

    현재 태그 속성이 있습니다. 마지막 행에서 언급 한 파인더를 사용할 수 있도록 해당 속성에 여러 값을 할당하는 가장 좋은 방법은 무엇입니까? – Pygmalion

    +0

    피그말리온 (Pygmalion)에서는 한 속성에 대해 여러 값을 사용할 수 없습니다. 'has_and_belongs_to_many' 관계는'join table'을 사용합니다. 종종 '매핑 테이블'이라고도합니다. 'has_and_belongs_to_many'에 대한 자세한 내용은 api : http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001836을 참조하십시오. –

    -1

    나는 이것이 당신이 원하는 것이라고 생각한다.

    @tag = params[:tag] 
    @supplies = Supply.find(:all, :conditions=>["? = ?", @tag, true], :order=>'name') 
    
    관련 문제