Rails 5最好的控制器动作来编写一个类似的查询

我想通过客户端的名称进行ajax搜索查询,所以我使用了like子句( 请参阅此问题 )。 我正在考虑使用索引操作来响应来自clients_controller的json格式,但我已经使用它来响应html格式,同时用will_paginatewill_paginate-bootstrap对我列出的行进行分页。

什么是最好的方法? 制作一个新的方法来响应json格式,还是应该使用索引格式? 以及如何做到这一点?

我是铁杆上的ruby新手

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变量上累积范围。

请记住,您的SQL查询仅在执行变量之类的Array方法时才发送到数据库,而不是之前。 所以你可以这样写:

 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 

您应该创建一个新的操作,其中包含一些富有成效的名称,例如searchsearch_by_client_name 。 它也将解决您的问题,您将坚持使用rails restful routing。

如果您希望索引操作同时为这两个请求提供服务,那么您可以执行以下操作:

 def index @client = Client.paginate(:page => params[:page]) respond_to do |format| format.html format.json do client = Client.where("client_name LIKE ? ", "%#{params[:client_name]}%" render json: { client: client } end end end