【问题标题】:Rails 3 or arel chain/merge SQL conditions conditionallyRails 3 或 arel 有条件地链接/合并 SQL 条件
【发布时间】:2013-04-30 07:48:40
【问题描述】:

Rails 3 中有没有一种方法可以在不进行字符串或数组合并的情况下有条件地合并记录条件?

例如:

    conditions = #?    
    if !params[:x].blank?
      # add a condition
    end
    if user.role?(:admin)
      # add a condition
    end
    if params[:y]
     # add a condition
    end
    etc
    result = Record.where(xx).group(:id).order(some_var) 
    # xx would merge all then group and order

【问题讨论】:

    标签: ruby-on-rails activerecord arel


    【解决方案1】:

    简单:

    # oh, the joy of lazy evaluation...
    result = Record.where(true) # I'd like to do Record.all, but that fetches the records eagerly!
    result = result.where("...") if params[:x].present?
    result = result.where("...") if user.role?(:admin)
    result = result.where("...") if params[:y].present?
    

    顺便说一句,不要在irb 中尝试这个:“read-eval-print”的“print”部分将强制评估记录集。

    编辑:我刚刚发现你可以使用Record.scoped,而不是Record.where(true)。不过,这在 Rails 4 中不起作用。

    【讨论】:

    • 没有问题。 enderlove 的arel 库让这样的事情成为可能——我认为这个库是真正的杰作。
    猜你喜欢
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-07
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多