Handling nested JSON in Rails without accepts_nested_attributes_for

I am creating a Rails application to provide the JSON API to the Backbone.js interface.

We have a number of cases where we provide data similar to label: { id: 1, name: "My Label" } . When this is used in the selection field on the form (to indicate an association), we currently need to indicate label_id: 1 in the published data. We would like the API to be more symmetrical and support the enclosed label: { id: 1 } form label: { id: 1 } , if possible.

So far, I (unsurprisingly) got an ActiveRecord::AssociationTypeMismatch error, because Rails expects a Label object and instead gets ActiveSupport::HashWithIndifferentAccess . I understand that we can use accepts_nested_attributes_for if we want to support nested label modification, but in this case I want to use only a nested form to indicate the correct label for the association.

Is there a good way to do this in Rails (3.2.8) that does not include modifying the params hash before passing it to the model? If not, any recommendations on the best way to reliably convert parameters as they become available?

Here's the current code that I use to smooth out the parameters in case this helps:

 def flatten_params(hash) hash.reduce({}) do |memo, (key, value)| if value.class == ActiveSupport::HashWithIndifferentAccess memo[(key.to_s + '_id').to_sym] = value['id'] else memo[key] = value end memo end end 
+4
source share
1 answer

with this question on SO, my buddy Omar says use ActiveSupport::JSON.decode(your_json) , and the second answer will work to get what you need.

0
source

Source: https://habr.com/ru/post/1442822/


All Articles