简体   繁体   English

红宝石像查询错误

[英]ruby like query error

This is my code for mysql like query: 这是我的MySQL查询代码:

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 development.log是

    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] . 您需要执行@query = params[:outlet][:query]

It is because params[:query] is nil, so the resulting sql is 这是因为params [:query]为nil,所以生成的sql是

where name like '%%' 

You do have a query parameter in params[:outlet][:query] which you could use without changing your view. 您确实在params [:outlet] [:query]中有一个查询参数,可以在不更改视图的情况下使用该参数。

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. 但是,由于您没有创建或更新Outlet,并且查询可能不是Outlet模型的属性,因此以这种方式构造表单实际上没有任何意义。

Try using form_tag instead of form_for and don't pass it an instance of Outlet. 尝试使用form_tag而不是form_for,并且不要将其传递给Outlet实例。 Also use text_field_tag instead of form.text_field. 还要使用text_field_tag而不是form.text_field。 This way params[:query] will be set, instead of being wrapped under params[:outlet]. 这样,将设置params [:query],而不是将其包装在params [:outlet]下。

The new form would look a bit like this: 新表格看起来像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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