Backbone and Rails associations: Avoiding JSON HashWithIndifferentAccess errors

后端 未结 2 1230
一整个雨季
一整个雨季 2021-02-01 00:08

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

2条回答
  •  被撕碎了的回忆
    2021-02-01 00:16

    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.

提交回复
热议问题