답변:
Note.
where(:user_id => current_user.id, :notetype => p[:note_type]).
where("date > ?", p[:date]).
order('date ASC, created_at ASC')
또는 모든 것을 SQL 표기법으로 변환 할 수도 있습니다.
Note.
where("user_id = ? AND notetype = ? AND date > ?", current_user.id, p[:note_type], p[:date]).
order('date ASC, created_at ASC')
where()합니다. 를 사용 where()하면 입력이 자동으로 이스케이프됩니다.
where()변수 대신 물음표가있는 위에 표시된 형식으로 사용되는 경우 입력을 자동으로 이스케이프하고 나중에 함수 호출에 나열합니다. 다음과 같이 사용하는 것은 안전하지 않습니다.Note.where("date > #{p[:date]}")
where("user_id = ?",current_user.id)보다 사용하는 것이 더 위험 합니다. 원시 SQL 표기법을 사용한다는 것은 테이블 설명을 직접 포함해야 함을 의미합니다 . 예 : . where(user_id: current_user.id)user_idwhere("notes.user_id = ?",current_user.id)
열 이름이 모호한 문제가 발생하면 다음을 수행 할 수 있습니다.
date_field = Note.arel_table[:date]
Note.where(user_id: current_user.id, notetype: p[:note_type]).
where(date_field.gt(p[:date])).
order(date_field.asc(), Note.arel_table[:created_at].asc())
다음을 사용해 볼 수 있습니다.
where(date: p[:date]..Float::INFINITY)
SQL에서 동등
WHERE (`date` >= p[:date])
결과는 다음과 같습니다.
Note.where(user_id: current_user.id, notetype: p[:note_type], date: p[:date]..Float::INFINITY).order(:fecha, :created_at)
그리고 나도 변했어
order('date ASC, created_at ASC')
에 대한
order(:fecha, :created_at)
Rails 6.1 은 where조건 에서 비교 연산자에 대한 새로운 '구문'을 추가했습니다 . 예를 들면 다음과 같습니다.
Post.where('id >': 9)
Post.where('id >=': 9)
Post.where('id <': 3)
Post.where('id <=': 3)
따라서 쿼리를 다음과 같이 다시 작성할 수 있습니다.
Note
.where(user_id: current_user.id, notetype: p[:note_type], 'date >', p[:date])
.order(date: :asc, created_at: :asc)
여기에 더 많은 예제를 찾을 수있는 PR 링크가 있습니다.