Reputation: 3200
I intend to update only one attribute of the color
model. The model has other attributes set to update via strong parameters:
def color_params
params.require(:color).permit(:product_id, :name, :instock)
end
This update method works fine when updating the attribute instock
without using strong parameters:
def update_stock
@color = Color.find(params[:selected_color])
if @color.update_attributes(instock: params[:new_stock])
flash[:success] = "Stock updated"
else
redirect_to root_path
end
end
To use strong parameters I replace if @color.update_attributes(instock: params[:new_stock])
with if @color.update_attributes(color_params)
. This returns the error ActionController::ParameterMissing (param is missing or the value is empty: color):
I suppose that the error is due to a model validation that requires product_id
presence.
A similar post Should we use strong params when we update only one attribute? does not have an accepted working solution.
Is there a risk of mass assignment when updating only one attribute and if so how do I use strong parameters in this case?
Upvotes: 1
Views: 1897
Reputation: 230521
I suppose that the error is due to a model validation that requires product_id presence
No, that's because your params are like this:
{ :instock => '1' }
And your strong params definitions requires them to be like this
{ :color => { :instock => '1' }
^^^^^^^^^
It's important to understand the purpose of strong params: whitelisting. When you cherry-pick just one param to be assigned, that is another type of whitelisting. So yes, it's safe to do this:
@color.update_attributes(instock: params[:new_stock])
Upvotes: 1