本文介绍了如何将 Ransack 与 find_by_sql 一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 Ransack 与find_by_sql"一起使用?我通常这样做:

How can I use Ransack with "find_by_sql"?I generally do this:

def index

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

end

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

Can I use Ransack when doing a custom query?:

@mymodels = Mymodel.find_by_sql(["SELECT ... ", current_user])

推荐答案

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

If I get it correctly, this is want you want:

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

虽然要直接回答您的问题,您可以将其转换为 SQL 字符串,但您不能(或很难)使用 current_user 作为参数:

To answer your question directly though, you can convert it to an SQL string, but you won't (or would be hard) be able to use current_user as an argument:

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

这篇关于如何将 Ransack 与 find_by_sql 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-14 02:03