Strong params in rails

340 views Asked by At

I removed mass assignment vulnerability of the below line :

friend = Friend.find(params[:id])
friend.update_attributes(params[:name])

by rewriting it as :

friend = Friend.find(params[:id])
friend.update_attributes(params.permit(:name))

But this gave me this error :

ActiveModel::MassAssignmentSecurity::Error (Can't mass-assign protected attributes for Friend: name):
Unpermitted parameters: id

Any idea why I am getting this error?

Edit :

I added attr_accessible :status_id and params.permit(:id, :name) and the error got removed. But is adding attr_accessible the right way to do it as we write strong params to remove this line, isn't it?

3

There are 3 answers

9
rob On

you should do

friend.update_attributes(params.require(:friend).permit(:name))

or put this into an private method

private
def object_params
  params.require(:friend).permit(:name)
end

and then call via

friend.update_attributes object_params

edit: i'm assuming that your params look like

{friend:{name:'xxxxx'},id:xx}
1
WhyEnBe On

Try updating your code as friend.update_attributes(params.permit(:name, :id)) to allow that parameter.

2
Chitra On

Don't write the attr_accessible in model, Rails 4 uses the strong parameter.

Try this code .

friend = Friend.find(params[:id])
friend.update_attributes(friend_params)

private

  def friend_params    
    params.require(:friend).permit!    
  end