代码之家  ›  专栏  ›  技术社区  ›  Massimiliano

如何使用Ransack和find\u by\u sql

  •  2
  • Massimiliano  · 技术社区  · 7 年前

    如何使用Ransack和“按sql查找”? 我通常会这样做:

    def index
    
      @m = Mymodel.ransack(params[:q])
      @mymodels = @m.result.page(params[:page]) 
    
    end
    

    在进行自定义查询时可以使用Ransack吗

    @mymodels = Mymodel.find_by_sql(["SELECT ... ", current_user])
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Jay-Ar Polidario    7 年前

    如果我理解正确,这就是你想要的:

    def index
      @m = Mymodel.ransack(params[:q])
      @mymodels = @m.result.page(param[:page]).where(user: current_user)
    end
    

    不过,为了直接回答您的问题,您可以将其转换为SQL字符串,但您无法(或将很难)使用 current_user

    def index
      @m = Mymodel.ransack(params[:q])
      sql = @m.result.page(param[:page]).to_sql
      @mymodels = Mymodel.find_by_sql(sql, current_user)
      # the line just above won't work immediately because you'll need to
      # modify the `sql` variable manually by inserting the `?` that you'll
      # need to map that to the `current_user` that you passed as an argument
    end