I\'m trying to get my backbone associations working inside a rails app , and I\'m having difficulty when trying to update existing models. Specifically, Rails throws the followi
I dealt with the same issue recently. It's actually not a HashWithIndifferentAccess error: it has to do with how accepts_nested_attributes_for
expects params.
When you declare accepts_nested_attributes_for :comments
, Rails looks for a parameter call comments_attributes
on the incoming params.
The problem is that your JSON representation coming from Backbone has a "comments"
property instead of a "comments_attributes"
property.
You could fix it on the Backbone side by adding a toJSON function to your Post model:
# in your Post model
toJSON: ->
attrs = _.clone(@attributes)
attrs.comments_attributes = _.clone(@attributes.comments)
delete attrs.comments
attrs
Or you could handle it in your Rails controller:
# in your Posts controller
def update
params[:comments_attributes] = params.delete(:comments) if params.has_key? :comments
# call to update_attributes and whatever else you need to do
end
Hopefully this helps.
For those who are Googling...
While the current accepted answer certainly works, the following was how I worked out my problem (very similar, but slightly different):
I was using a nested form, with models nested 4 layers deep. In my controller which was rendering the form, I needed to build out the form.
def new
@survey = Survey.new
3.times do
question = @survey.questions.build
4.times { question.answers.build }
end
end
This allowed the params to include params[:survey][:questions_attributes]
. Rails renamed the parameters for me because I informed it ahead of time.
Hope this helps!