I have this search in Rails 3:
Note.where(:user_id => current_user.id, :notetype => p[:note_type], :date => p[:date]).order('date ASC, created_at ASC')
But I need the :date => p[:date]
condition to be equivilent to :date > p[:date]
. How can I do this? Thanks for reading.
This question is related to
ruby-on-rails
activerecord
ruby-on-rails-3
You can try to use:
where(date: p[:date]..Float::INFINITY)
equivalent in sql
WHERE (`date` >= p[:date])
The result is:
Note.where(user_id: current_user.id, notetype: p[:note_type], date: p[:date]..Float::INFINITY).order(:fecha, :created_at)
And I have changed too
order('date ASC, created_at ASC')
For
order(:fecha, :created_at)
If you hit problems where column names are ambiguous, you can do:
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())
Rails 6.1 added a new 'syntax' for comparison operators in where
conditions, for example:
Post.where('id >': 9)
Post.where('id >=': 9)
Post.where('id <': 3)
Post.where('id <=': 3)
So your query can be rewritten as follows:
Note
.where(user_id: current_user.id, notetype: p[:note_type], 'date >', p[:date])
.order(date: :asc, created_at: :asc)
Here is a link to PR where you can find more examples.
If you aren't a fan of passing in a string, I prefer how @sesperanto has done it, except to make it even more concise, you could drop Float::INFINITY
in the date range and instead simply use created_at: p[:date]..
Note.where(
user_id: current_user.id,
notetype: p[:note_type],
created_at: p[:date]..
).order(:date, :created_at)
Take note that this will change the query to be >=
instead of >
. If that's a concern, you could always add a unit of time to the date by running something like p[:date] + 1.day..
Source: Stackoverflow.com