2

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.

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?

I'm new with ruby on rails

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
Community
  • 1
  • 1
Cloud1988
  • 199
  • 2
  • 11

2 Answers2

3

In my opinion, you should keep only your index action and just accumulate the scopes on your @client variable.

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
Nicolas Blanco
  • 11,164
  • 7
  • 38
  • 49
0

You should create a new action with some fruitful name like search or search_by_client_name . It will solve your issue also and you will stick with rails restful routing.

If you want index action to serve both request then you can do something like this:

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
Dipak Gupta
  • 7,321
  • 1
  • 20
  • 32