【问题标题】:Undefined method `stringify_keys' for "4":String“4”的未定义方法“stringify_keys”:字符串
【发布时间】:2015-02-06 09:34:26
【问题描述】:

好的,这似乎是一个很常见的问题,但是在网上查找我的示例似乎找不到解决方案。

当尝试使用以下代码更新对象(产品)时,我得到 undefined method `stringify_keys' for "4":String NoMethod 错误页面被 Rails 抛出。

这里是代码,看看你是否能指出我做错了什么:

产品控制器

  def update
  @product = Product.find(params[:id])

  if @product.update(params[:id])
    redirect_to @product
  else
    render 'edit'
  end
end

编辑表单视图:

<%= form_for(@product.id) do |f| %>

  <% end %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :price %><br>
    <%= f.text_field :price %>
  </div>
  <div class="field">
    <%= f.label :descriptio %><br>
    <%= f.text_field :description %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

我希望我可以让它工作!

【问题讨论】:

  • 这行if @product.update(params[:id])是错的,应该是if @product.update(params[:product])
  • @product.update_attributes(params[:product])
  • @Pavan 不确定您是否愿意将其作为答案,以便我感谢您的帮助。很好的答案,非常感谢!

标签: ruby-on-rails


【解决方案1】:

这个片段不正确。

def update
  @product = Product.find(params[:id])

  if @product.update(params[:id])
    redirect_to @product
  else
    render 'edit'
  end
end

update 需要 Hash 的属性,您传递的是 Fixnum ID。应该是

@product.update(params[:product])

理想情况下,您还应该按照强参数功能的要求过滤输入。

@product.update(product_params)

def product_params
  params.require(:product).permit(...)
end

【讨论】:

    【解决方案2】:

    有几件事是错误的。 Simone 在他的回答中提到了一个。

    如果确实如您发布的那样,则您的编辑表单不正确。

    <%= form_for(@product) do |f| %>   <-- no .id
    

    表单是产品模型的一个实例,而不是 FixNum。

    form-for 之后的 关闭该表单。

    描述标签与文本字段不匹配。

    也许你打算:

    <%= form_for(@product) do |f| %>
      <div class="field">
        <%= f.label :name %><br>
        <%= f.text_field :name %>
      </div>
      <div class="field">
        <%= f.label :price %><br>
        <%= f.text_field :price %>
      </div>
      <div class="field">
        <%= f.label :description %><br>
        <%= f.text_field :description %>
      </div>
      <div class="actions">
        <%= f.submit %>
      </div>
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多