2017-10-10 39 views
0

如何使用Ransack和「find_by_sql」? 我一般這樣做:如何使用Ransack和find_by_sql

def index 

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

end 

我可以用洗劫做一個自定義查詢?:

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

也許使用範圍,https://github.com/activerecord-hackery/ransack#using-scopesclass-methods – vzamanillo

回答

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