"titleofcoolstuff":String 的未定义方法“允许”

undefined method `permit' for "titleofcoolstuff":String

我只是想从视图中获取两个参数到我的控制器。我正在使用 Rails 4.2.x 强大的参数让我很痛苦。

一个参数 :query 正确解析。然而,第二个参数 :location 在问题标题中抛出错误。我用谷歌搜索了这个问题,但每个人的情况似乎都不同,他们的解决方案(相对)独特。

有问题的视图是 index.html.erb,它只包含一个简单的搜索表单。

<%= form_tag("/searches", action: "create", method: "post") do %>
          <div>Job Title</div>
          <%= text_field_tag(:query) %>
          <div>Location</div>
          <%= text_field_tag(:location) %>
          <%= submit_tag("Go") %>
<% end %>

有问题的控制器是 searches_controller.rb

class SearchesController < ApplicationController
        def index
                binding.pry
        end

        def show
                binding.pry
        end

        def update
        end

        def create
                @query = search_params["query"].to_s || nil
                @location = search_params[:location].to_s || nil
                binding.pry
        end

        def delete
        end

        private

        def search_params
                params.require(:query).permit(:location)
        end
end

堆栈跟踪指向 search_params 方法,并显示我在控制器中有以下参数

{ "utf8"=>"✓", "authenticity_token"=>"DEcTwT/NnSY3S3n25zZGXD+KRZcsRkWj9bmN57AMNivFbMXwHF5Vf/psgzSMkZPBa+OWJgafXYGdW+o5KN3xxg==", "query"=>"titleofcoolstuff", "location"=>"milwauke", "commit"=>"Go" }

我错过了什么?

强参数用于提供属性的散列,例如:

<%= form_for @user do |f| %>
 ## form
<% end %>

这可能会发送这样的参数:

 "user" => { "name"=> "Your Name", "age" => "23", "location" => "USA" }

在这种情况下,强参数将指示 rails 处理属性的 users 散列,特别是这些属性,如下所示:

params.require(:user).permit(:name, :age, :location)

在你的例子中,你传递的是单独的参数(不是属性的散列),所以如果你想获取它们,你可以明确地获取它们:

def create
  @query = params[:query].to_s || nil
  @location = params[:location].to_s || nil
  #do something
end

这里不需要强参数来将模型属性列入白名单。希望这有帮助。

你的情况

"query"=>"titleofcoolstuff",
"location"=>"milwauke",
"commit"=>"Go"

因为您的数据没有用任何密钥包裹(它们在根目录中)所以您可以简单地使用 params[:query].

来访问它们

Whitelisting/Strong参数

我们只需要将参数列入白名单以进行批量分配。像 @user.update(user_params) 这里,除非用户在 user_params 中发送的参数被列入白名单,即允许使用 .permit 方法; update 方法将抛出异常 ActiveModel::ForbiddenAttributes.

在你的情况下,因为你没有更新任何东西,所以你不需要为它创建强参数。

 def create
   @query = params["query"].to_s || nil
   @location = params[:location].to_s || nil
   binding.pry
  end

If you are gonna do mass assignment in future you have to whitelist your params

有关详细信息,请参阅 https://cbabhusal.wordpress.com/2015/10/02/rails-strong-params-whilisting-params-implementation-details/