skyw
skyw

Reputation: 369

Saving a hash literal (telling Rails not to interpret hash as a nested attribute)?

I think Rails is interpreting my hash literal as a nested attribute. I would actually just like to convert the hash to a string. It's not a nested attribute related to some model, nor should it be related to a model. Here, nesting the values is merely a convenient way to pass data through a form without too much busywork.

:params was

{"utf8"=>"✓",
 "authenticity_token"=>"[deleted for SO]",
 "scorecard"=>{"1"=>"2",
 "2"=>"2",
 "3"=>"2",
 "4"=>"2",
 "5"=>"2",
 "6"=>"2",
 "7"=>"2",
 "8"=>"2",
 "9"=>"2",
 "10"=>"2",
 "11"=>"2",
 "12"=>"2"}},
 "commit"=>"Create Assessment"}

.. but when I do:

assessment = Assessment.new(params[:assessment])
...
@assessment.save

... I get:

unknown attribute: scorecard

Interestingly, when

attr_accessible :scorecards

.. is in the model (note plural form), I get:

Can't mass-assign protected attributes: scorecard

Since when attr_accessible is what I actually want (:scorecard), I get "unknown attribute: scorecard", it seems Rails thinks it's dealing with a nested attribute.

Can I tell Rails not to treat :scorecard as a nested attribute?

Thanks.

Upvotes: 0

Views: 191

Answers (2)

Yunwei.W
Yunwei.W

Reputation: 1599

Can you post your column names of the table? It seems that you are missing the column 'scorecard'. Or did you name it as 'scorecards' ? Just in case.

Also you have to declare serialized :scorecard to save a serialized value. Saving it as a JSON is also an option. Just need additional parsing.

Upvotes: 1

strider
strider

Reputation: 5954

did you mean to leave out the 's' in attr_accessible?

attr_accessible :scorecard(s)

EDIT

you many be getting this next error because you are missing a scorecard column on your table

unknown attribute: scorecard

Upvotes: 1

Related Questions