Can't mass-assign protected attributes: user

。_饼干妹妹 提交于 2019-12-13 14:09:24

问题


I'm working on a simple app that requires me to submit a form. I created two models.

user.rb

class User < ActiveRecord::Base
  attr_accessible :email

  has_many :item
end

item.rb

class Item < ActiveRecord::Base
  attr_accessible :user_id

  belongs_to :user
end

Instead of creating a user using the user form view, I'm trying to create the user using the item form view.

items/_form.html.haml

= nested_form_for @item do |form|

  = form.fields_for :user do |builder|
    = builder.text_field :email

  = form.submit "Save"

Did I miss something here? I'm using nested_form_for btw. Thank you.


回答1:


Try this

attr_accessible :email :user



回答2:


Try out this code

class Item < ActiveRecord::Base
  attr_accessible :user_id
  accepts_nested_attributes_for :user      # <--- This should help

  belongs_to :user
end 

class User < ActiveRecord::Base
  attr_accessible :email

  has_many :items                          # <--- Typofix
end



回答3:


Found the answer to my problem.

I updated my items_controller.rb

def new
  @item = Item.new
  @item.user = User.new # I added this line.
end

Then I updated the item.rb

class Item < ActiveRecord::Base
  attr_accessible :user_attributes

  belongs_to :user
  accepts_nested_attributes_for :user
end


来源:https://stackoverflow.com/questions/12447937/cant-mass-assign-protected-attributes-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!