Can you do greater than comparison on a date in a Rails 3 search?

后端 未结 4 388
天命终不由人
天命终不由人 2020-12-04 08:52

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 A         


        
相关标签:
4条回答
  • 2020-12-04 09:30
    Note.
      where(:user_id => current_user.id, :notetype => p[:note_type]).
      where("date > ?", p[:date]).
      order('date ASC, created_at ASC')
    

    or you can also convert everything into the SQL notation

    Note.
      where("user_id = ? AND notetype = ? AND date > ?", current_user.id, p[:note_type], p[:date]).
      order('date ASC, created_at ASC')
    
    0 讨论(0)
  • 2020-12-04 09:35

    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)
    
    0 讨论(0)
  • 2020-12-04 09:40

    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())
    
    0 讨论(0)
  • 2020-12-04 09:48

    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.

    0 讨论(0)
提交回复
热议问题