【问题标题】:Nested Attribute one-to-one different mass-assign error嵌套属性一对一不同的质量分配错误
【发布时间】:2013-07-20 09:40:43
【问题描述】:

在我的应用中,用户拥有一个位置,位置属于用户。

user.rb

has_one :location
accepts_nested_attributes_for :location

attr_accessible ... :location_attributes

location.rb

belongs_to :user

attr_accessible :country, :state, :city, :address, :zipcode, :user_id

users_controller(用户是自动创建的,因此没有“新”视图)

def edit
  @user = current_user
  @user.build_location
end

users/edit.html.haml

= form_for @user do |f|

... 

  = f.fields_for :location do |location|
    %p  
      = location.label :country
      = location.text_field :country

    %p  
      = location.label :state
      = location.text_field :state

    %p  
      = location.label :city
      = location.text_field :city

    %p  
      = location.label :address
      = location.text_field :address

    %p
      = location.label :zipcode
      = location.text_field :zipcode  
  = f.submit

我收到的错误是“无法批量分配受保护的属性:国家、州、城市、地址、邮政编码。”

我之前遇到过“无法批量分配受保护的属性:location_attribute”类型的错误,但这不是问题所在。

这是我的(删节的)参数:

{"utf8"=>"✓", "_method"=>"put", "authenticity_token"=>"RTpnMsKuByhnGgs9xrX3d0nzKzcaqIcpS75tsujPX2s=", "user"=>{"name"=>"myname", ... "location_attributes"=>{"country"=>"USA", "state"=>"whatever", "city"=>"", "address"=>"", "zipcode"=>""}}, "commit"=>"Update account", "action"=>"update", "controller"=>"users", "id"=>"219"}

知道这里发生了什么吗?我已经搜索了一个 WHILE,但似乎找不到有这个问题的人(everyoneelsehasthe latter mass-assign one)。

【问题讨论】:

  • 我认为您不需要将 location_attributes 定义为 attr_accessible
  • 愚蠢的想法,但服务器重启? ;)
  • 还有 - 那是哪个 Rails 版本?
  • 3.2,是的。我试过重启一堆。

标签: ruby-on-rails ruby-on-rails-3 nested-forms nested-attributes


【解决方案1】:

这实际上是控制器中更新操作的问题,它使用了管理标志 --

if user.update_attributes(params[:user], as: :admin)

-- 出于特定应用的原因。奇怪的是,如果我拿走那面旗帜,它工作得很好。所以我必须想办法解决这个问题——如果位置也在更新,不要管理员更新。以防万一有人遇到类似的事情。

【讨论】:

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