Rails 5最佳控制器操作,以编写类似查询 [英] Rails 5 best controller action to write a like query
问题描述
我想通过客户名称进行ajax搜索查询,因此我使用了like子句(请参阅此问题).我当时在考虑使用index动作来响应来自clients_controller的json格式,但是我已经在使用它来响应html格式,同时用 will_paginate 和 will_paginate对我列出的行进行分页-bootstrap .
I want to make an ajax search query by a client's name, so I'm using a like clause (see this question). I was thinking of using the index action to respond to json format from clients_controller but I'm already using it to repond to html format and at the same time paginates my listed rows with will_paginate and will_paginate-bootstrap.
什么是最好的方法?做一个新的方法来响应json格式,或者我应该使用带有格式的索引一?以及如何做到这一点?
What is the best way? making a new method to respond to json format or should I use the index one with format? and How to do that?
我是红宝石新手
clients_controller.rb
def index
respond_to do |format|
format.html
{
#something like this I know that I would return me a syntax error
@client = Client.paginate(:page => params[:page])
}
format.json
{
#something like this I know that I would return me a syntax error
@client = Client.where("client_name LIKE ? ", "%#{params[:client_name]}%" )
}
end
end
def other_method
@client = Client.where("client_name LIKE ? ", "%#{params[:client_name]}%" )
respond_to do |format|
format.json {...}
end
end
推荐答案
在我看来,您应该只保留index
动作,而只需累积@client
变量的作用域即可.
In my opinion, you should keep only your index
action and just accumulate the scopes on your @client
variable.
请记住,仅当对变量执行像each
这样的Array方法时才将SQL查询发送到数据库,而不是之前.
因此,您可以编写如下内容:
Remember that your SQL query is only sent to the database when performing an Array method like each
on your variable, not before.
So you can write something like:
def index
@client = Client.all
if params[:client_name].present?
@client = @client.where("client_name LIKE ? ", "%#{params[:client_name]}%")
else
@client = @client.paginate(page: params[:page])
end
respond_to do |format|
format.html
format.json
end
end
这篇关于Rails 5最佳控制器操作,以编写类似查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!