Reputation: 444
I am using a form_for loop to submit data to my controller’s create method. In the form_for I have several text_fields that are not associated to any field on the table. They are essentially free text fields that I want to put data in and use for additional logic in the create method.
When I submit the form, the first line of the create is hit:
@user = User.new(params[:user])
The following error occurs (:test1 being my form field unrelated to the model):
Can't mass-assign protected attributes: test1
I realize it is because of the text fields I’m sending that are not related to the model. I have tried all sorts of strange syntaxes such as:
User.new(params.require(:user).except(:test1))
and User.new(params[:user].except(:test1))
to no avail.
I’ve found several sources online stating you can use the except or delete method but I can’t seem to get it to work, especially while in the User.new().
I have tried it outside the new as well:
params.delete(:test1)
@user = User.new(params[:xref_ability])
I also want to be able to read the additional attributes eventually in the create, so I don’t think the except() or delete() is going to solve all my issues (if it did work). Therefore, I tried attr_accessor :test1 on the controller class and the model class hoping it would give the method permission to read the attribute, but no success.
I've also tried adding it to attr_accessible on my model which then leads to the error:
unknown attribute: test1
Any other suggestions?
Upvotes: 1
Views: 121
Reputation: 1270
Maybe try using virtual attributes? It makes sense to use them if they don't map to a field in the DB.
RB has a good railscast on the topic: http://railscasts.com/episodes/16-virtual-attributes-revised
Upvotes: 1
Reputation: 2396
You are getting the unknown attribute error because it doesn't exist in the database.
You must create test1 in database (add it with a migration...) or just add it to your model with:
attr_accessor :test1
This way you'll have the value in the object but it won't store in the database. If you need to store it, add it to the database and use attr_accessible as @Miguelgraz told you before.
Upvotes: 0
Reputation: 4436
You probably need a attr_accessible :test1
on your User model, give it a try.
Upvotes: 1