I am building a Rails application to provide a JSON API to a Backbone.js frontend.
We have a number of cases where we provide data similar to label: { id: 1, name: "My Label" }
. When this is used in a select box within a form (to specify an association) we currently need to specify label_id: 1
in posted data. We'd like the API to be more symmetrical and support the nested label: { id: 1 }
form if possible.
So far, I (not surprisingly) get a ActiveRecord::AssociationTypeMismatch
error as Rails is expecting a Label
object and receives a ActiveSupport::HashWithIndifferentAccess
instead. I understand we can use accepts_nested_attributes_for
if we want to support nested modification of the labels, but in this case I only want to use the nested form to specify the correct label for the association.
Is there a good way to do this in Rails (3.2.8) that doesn't involve modifying the params hash before passing it off to the model? If not, any recommendations for the best way to robustly transform the params as they come in?
Here's the current code I use to flatten out the params in case it is of help:
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