简体   繁体   中英

ruby like query error

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)

Looking at the log file and below trace :-

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

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

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 %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM