【问题标题】:How o use Ransack with find_by_sql如何将 Ransack 与 find_by_sql 一起使用
【发布时间】:2017-10-10 08:53:48
【问题描述】:

如何将 Ransack 与“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])

【问题讨论】:

标签: ruby-on-rails ransack


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2014-03-02
    • 2012-02-06
    • 1970-01-01
    • 2011-11-27
    • 2011-02-01
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多