2

This is my code for mysql like query:

def search
    params.permit!
    @query = params[:query]
    respond_to do |format|
        @outlet = Outlet.select(:name).where("name like ?","%#{@query}%")
        format.json { render json: @outlet }
    end
end

It renders all of my data from table. It does not respond to the query. Do you have any ideas?

My route is:

 namespace :api do
  resources :outlets, :defaults => { :format => 'json'}
  get 'outlets/auto_complete' => 'outlets#auto_complete', :defaults =>       { :format => 'json'}
  post 'outlets/search' => 'outlets#search', :defaults => { :format => 'json' }

 end

The development.log is

    Started POST "/api/outlets/search" for 127.0.0.1 at 2015-05-30 16:56:22 +0530
Processing by Api::OutletsController#search as JSON
  Parameters: {"outlet"=>{"query"=>"life"}}
  [1m[35mOutlet Load (0.1ms)[0m  SELECT `outlets`.`name` FROM `outlets`  WHERE (name like '%%')
Completed 200 OK in 28ms (Views: 22.3ms | ActiveRecord: 1.7ms)
10
  • it render all of my data form the table,.. the query is not working Commented May 30, 2015 at 11:13
  • show what data you are passing via params[:query],,, show the console log.. Commented May 30, 2015 at 11:14
  • i'm using postmen rest client,.. the params i'm passing is outlets[:query] value is 'something' Commented May 30, 2015 at 11:16
  • 1
    probably the value you are passing matched all records.. that's why. But I am sure query is working. Commented May 30, 2015 at 11:17
  • no,.. the value i'm passing is very particular in one data Commented May 30, 2015 at 11:19

2 Answers 2

4

Looking at the log file and below trace :-

Parameters: {"outlet"=>{"query"=>"life"}}

I found the issue. You need to do @query = params[:outlet][:query].

Sign up to request clarification or add additional context in comments.

Comments

1

It is because params[:query] is nil, so the resulting sql is

where name like '%%' 

You do have a query parameter in params[:outlet][:query] which you could use without changing your view.

However, as you're not creating or updating an Outlet, and query probably isn't an attribute of the Outlet model, it doesn't really make sense to structure the form in this way.

Try using form_tag instead of form_for and don't pass it an instance of Outlet. Also use text_field_tag instead of form.text_field. This way params[:query] will be set, instead of being wrapped under params[:outlet].

The new form would look a bit like this:

<%= form_tag do %>
  <%= text_field_tag :query %>
  <%= submit_tag %>
<% end %>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.