Rails没有更新属性

时间:2013-10-21 03:58:51

标签: ruby-on-rails devise

我认为非常标准的更新,但在提交put请求时,属性不会更新。这是我的相关模型:

class Vendor < ActiveRecord::Base

    geocoded_by :address
    after_validation :geocode,
        :if => lambda{ |obj| obj.address_changed? }
end

我的控制器方法:

def edit
    @vendor = Vendor.find(params[:id])
end

def update
    @vendor = Vendor.find(params[:id])
    if @vendor.update_attributes(vendor_params)
        redirect_to vendors_mgmt_path

    else
        render 'edit'
    end
end

def vendor_params
    params.permit(:id, :name, :address, :image, :latitude, :longituded )
end

我在尝试更新后在服务器日志中看到了这一点:

Started PUT "/vendors/1" for 127.0.0.1 at 2013-10-20 20:44:54 -0700
Processing by VendorsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"fTbZVEfckQz4xQzY5xSMQCArrGZqymNsVeyic/PXKcE=", "vendor"=>{"name"=>"Store", "address"=>"1221 E. Main St."}, "commit"=>"Save changes", "id"=>"1"}
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
  Vendor Load (0.2ms)  SELECT "vendors".* FROM "vendors" WHERE "vendors"."id" = ? LIMIT 1  [["id", "1"]]
Unpermitted parameters: utf8, _method, authenticity_token, vendor, commit
   (0.1ms)  begin transaction
   (0.1ms)  commit transaction
Redirected to http://localhost:3000/vendors/mgmt
Completed 302 Found in 10ms (ActiveRecord: 0.6ms)

这让我感到困惑,因为Vendor表单看起来像这样,并且没有真实性令牌等。

<h1>Update <%= "#{@vendor.name}" %></h1>

<%= form_for(@vendor) do |f| %>
    <%= f.label :name %>
    <%= f.text_field :name %>

    <%= f.label :address %>
    <%= f.text_field :address %>

    <%= f.label :Logo %>
    <%= f.file_field :image %>

    <%= f.submit "Save changes", class: "btn btn-success" %>
<% end %>

有人看到任何明显错误吗?任何帮助深表感谢。提前谢谢!

1 个答案:

答案 0 :(得分:2)

默认情况下,Rails包含所有形式的某些隐藏字段,例如authenticity_token,用于停止CSRF。 (更多信息here)我建议更改一行:

params.permit(:id, :name, :address, :image, :latitude, :longituded )

为:

params.require(:vendor).permit(:id, :name, :address, :image, :latitude, :longituded)

在控制器中更改此行应该允许表单提交的其他参数,而不仅仅是vendor参数中的参数。

另外,你拼错了“经度”,我不确定这是否会造成任何额外的麻烦,或者你的问题只是一个错字。