ActiveRecord 또는 쿼리 해시 표기법
where
ActiveRecord 메서드에 인수를 제공하는 세 가지 주요 표기법이 있음을 알고 있습니다 .
- 순수한 문자열
- 정렬
- 해시시
지정 and
위한 where
방법은 정직 :
# Pure String notation
Person.where("name = 'Neil' AND age = 27")
# Array notation
Person.where(["name = ? AND age = ?", 'Neil', 27])
# Hash notation
Person.where({name: "Neil", age: 27})
or
이 동일한 where
방법을 지정 하는 것은 해시 구문에 대해 저를 괴롭 힙니다. 가능합니까?
# Pure String notation
Person.where("name = 'Neil' OR age = 27")
# Array notation
Person.where(["name = ? OR age = ?", 'Neil', 27])
# Hash notation DOESN'T WORK
Person.where({name: "Neil" OR age: 27})
«해시 표기법»(마지막이 좀 hash-이다 구현으로 간주 될 수있는 5 개 가지 옵션이 있습니다 틱 ) :
Ruby on Rails 5에서는
ActiveRecord::Relation#or
메소드를 사용하여 다음 연결을 수행 할 수 있습니다 .Person.where(name: 'Neil').or(Person.where(age: 27))
where_values
와 함께 사용하십시오reduce
.unscoped
방법이 필요 레일 4.1 단지에 대한 보장default_scope
에 포함되지 않는다where_values
. 그렇지 않으면 모두에서 술어default_scope
와where
와 체인으로 연결된 것or
운영자 :Person.where( Person.unscoped.where(name: ['Neil'], age: [27]).where_values.reduce(:or) )
다음과 같은 기능이나 유사한 기능을 구현하는 타사 플러그인을 설치합니다.
Where Or (
.or
위에서 언급 한 Ruby on Rails 5 기능의 백 포트 )-
Person.where{(name == 'Neil') | (age == 27)}
-
Person.where(name: 'Neil').or(age: 27)
-
Person.where.anyof(name: 'Neil', age: 27)
-
Person.where( (SmartTuple.new(' or ') << {name: 'Neil', age: 27}).compile )
Arel 사용 :
Person.where( Person.arel_table[:name].eq('Neil').or( Person.arel_table[:age].eq(27) ) )
명명 된 매개 변수와 함께 준비된 명령문을 사용하십시오.
Person.where('name = :name or age = :age', name: 'Neil', age: 27)
Potashin이 말했듯이이 기능을 구현하는 다른 타사 플러그인을 사용할 수 있습니다. 나는 Squeel을 오랫동안 사용 했으며 이것과 복잡한 하위 쿼리 또는 조인과 같은 훨씬 더 많은 기능에 대해 잘 작동합니다.
That query using squeel:
@people= Person.where{(name == 'Neil') | (age = 27)}
참고URL : https://stackoverflow.com/questions/31096009/activerecord-or-query-hash-notation
'Nice programing' 카테고리의 다른 글
중첩 된 목록 이해 이해 (0) | 2020.10.26 |
---|---|
Julia의 잘못 작성된 R 예제 속도 향상 (0) | 2020.10.26 |
따옴표로 정규식을 bash? (0) | 2020.10.26 |
파이썬에 대한 일반적인 캐치 (0) | 2020.10.26 |
1 시간보다 오래된 -mtime 파일 찾기 (0) | 2020.10.26 |