How to add conditional where clauses in rails

前端 未结 2 1915
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 20:50

I am a rails newbie and am trying to perform a search on a table with rails, and i\'m just using my sql knowledge to do this. But this just doesn\'t seems like rails or ruby

相关标签:
2条回答
  • 2020-12-09 21:14

    You can apply multiple where calls to a query so you can build your base query:

    query = User.joins(...)
                .group(...)
                .select(...)
                .where('users.id = :user_id', :user_id => self.id)
    

    and then add another where call depending on your date interval:

    if(begin_date && end_date)
      query = query.where(:created_at => begin_date .. end_date)
      # or where('created_at between :begin_date and :end_date', :begin_date => begin_date, :end_date => end_date)
    elsif(begin_date)
      query = query.where('created_at >= :begin_date', :begin_date => begin_date)
    elsif(end_date)
      query = query.where('created_at <= :end_date', :end_date => end_date)
    end
    

    Each where call adds another piece to your overall WHERE clause using AND so something like:

    q = M.where(a).where(b).where(c)
    

    is the same as saying WHERE a AND b AND c.

    0 讨论(0)
  • 2020-12-09 21:20

    I cant think of a great reason why you would actually want to generate SQL in your code. Active record seems like a much more efficient solution for your needs, unless there is a reason why you cant use that.

    Link explaining how to join tables with active record

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