问题
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