我们如何通过路线将参数传递给动作?

时间:2017-11-07 23:01:28

标签: ruby-on-rails

我正试图通过路径将某些内容传递给params哈希。我的代码是:

的routes.rb

get :search, controller: :restaurants

restaurants_controller.rb

before_action :force_json, only: :search

def search
    @restaurants = Restaurant.where("name LIKE ?", "%#{params[:q]}%").limit(5)
end

private

    def force_json
      request.format = :json
    end

由于before操作,我们不应该将路径称为search.json;仅search就足够了。但是,当我尝试将参数:q传递给params哈希时,如下所示:

localhost:3000/search&q=A

我最终得到了这个错误:

No route matches [GET] "/search&q=A"

2 个答案:

答案 0 :(得分:1)

您的查询字符串结构不正确。

localhost:3000/search?q=a

更多信息:https://en.wikipedia.org/wiki/Query_string#Structure

答案 1 :(得分:1)

好吧,如果您在查询字符串中表示您应该将其作为

传递
localhost:3000/search?q=A

否则,您可以将参数放在路线定义中

get 'search/:q'