I am building a rails4 api where i am posting a nested hash of attributes. however, the model does not actually have nested attributes or an association. Attempting to make a cleaner post params hash by combining some attributes into a group, but have the api handle the unwrapping and strong parameters validation.
## Example POST params
params[:item][:group] = {
a: true,
b: false
}
But the model does not actually have a group
column, the attributes a
and b
are attributes directly on the model.
to handle this without the group
wrapper would simply be
params.require(:item).permit(:a, :b)
But I would like to have it pass strong_parameters
submitted with the group
wrapper. How can I achieve this but having the POST params as mentioned above?
like most ruby/rails situations there's likely a better way of doing this. grabbing from the responses i end up with this seemingly hack approach. the important thing is that it does what i'm looking for, but it feels icky so if someone has a more elegant way please share!
class YourController < ApplicationController
private
## POST { item: { group: { a: true, b: false } } }
def item_params
group = params[:item][:group].presence
if group
## Unwrap nesting and place at root of params[:item]
## Probably should explicitly handle this instead of iterating
group.each {|k,v| params[:item][k] = v }
params[:item].delete :group
end
params[:item].permit(:a, :b)
end
end