使用MySQL的LIKE查询总是返回nil

时间:2017-01-23 11:59:31

标签: ruby-on-rails ruby-on-rails-4

首先,我使用的是rails 4.

我要做的是在我的MySQL数据库中搜索一些用户名。

但无论我的查询是什么,@ search都是nil,结果是404。

这是我的代码。

我用我的参数[:查询]尝试了一些更改,例如

“%#{params [:query]}%”或只是没有“%”的params [:query]。

但它仍然无效

任何帮助将不胜感激。

def search_user
        @searh=User.where('username LIKE ?', "%"+params[:query]+"%").all
        if @search == nil 
            then
            head 404, content_type: "text/html"
            else
            render json: @search.to_json, status: 200
        end
    end

2 个答案:

答案 0 :(得分:2)

    def search_user
      @searh=User.where('username LIKE ?', "%#{params[:query]}%").all
        if @search == nil 
            then
            head 404, content_type: "text/html"
            else
            render json: @search.to_json, status: 200
        end
    end

我希望它可以在您的代码中使用。

答案 1 :(得分:0)

我总是喜欢它:

@searh=User.where('username LIKE ?', "'%#{params[:query]}%'")

请注意,生成SQL查询时,模式将以单引号为界:

username LIKE '%whatever%'