如何使用Ransack与find_by_sql

时间:2017-10-10 08:53:49

标签: ruby-on-rails ransack

如何使用Ransack和#34; find_by_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 个答案:

答案 0 :(得分:0)

如果我弄错了,这就是你想要的:

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