params[:post]
is actually string in your case. It's not a hash. That's why it is not working.
Ruby On Rails - Remove attribute from model
-
27-06-2022 - |
Question
I'm trying to remove an attribute from params before to update an object, but i don't succeed to do it.
Params contain an object Post, and i want to remove image_url from it :
{
"post" : "{
\"content\" : \"dfsgdfa\",
\"created_at\" : \"2013-09-01T08:39:26Z\",
\"id\" : 21,
\"image_content_type\" : \"image/jpeg\",
\"image_file_name\" : \"img.jpg\",
\"image_file_size\" : 61140,
\"image_updated_at\" : \"2013-09-01T08:39:26Z\",
\"title\" : \"sdsdsdd\",
\"updated_at\" : \"2013-09-01T08:39:26Z\",
\"user_id\" : 4,
\"image_url\" : \"/system/posts/images/000/000/021/original/img.jpg?137802476
\"}",
"image" : "null",
"action" : "update",
"controller" : "posts",
"id" : "21"
}
So i did like that :
params[:post].delete("image_url")
No errors are raised, but image_url is still in params[:post]
How can i delete it ?
Solution
OTHER TIPS
params[:post] is not a hash, when you inspect it over controller it will look like hash. It's actually ActiveSupport::HashWithIndifferentAccess instance.
You can not remove a key/value pair from a Hash using Hash#delete: you should to write before save callback
def delete_image_url
params[:post].delete :image_url
end
I hope it will help you. I already tested it.
You can pass a subset into whatever function you want with:
@object = Foo.new(params.reject{|key,value| key == 'image_url'})
This doesn't remove it entirely from params, but returns a copy without that key
params['post'].delete("image_url")