Search code examples
ruby-on-railsransack

How o use Ransack with 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

Can I use Ransack when doing a custom query?:

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

Solution

  • 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