How o use Ransack with find_by_sql

本秂侑毒 提交于 2019-12-20 04:52:07

问题


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

Can I use Ransack when doing a custom query?:

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

回答1:


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

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


来源:https://stackoverflow.com/questions/46662465/how-o-use-ransack-with-find-by-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!