robertwbradford
robertwbradford

Reputation: 6605

In a Rails 4 controller, thing_params.delete(:something) is not deleting the :something key-value pair

I have the following in a controller:

# app/controllers/things_controller.rb

def create 
  kind = thing_params.delete(:kind)
  detail_attributes = thing_params.delete(:detail_attributes)
  @detail = Detail.create(kind, detail_attributes)
  @thing = current_user.things.build(thing_params)
  ...
end


private

def thing_params
  params.require(:thing).permit(
    :name,
    :position,
    :kind,
    { detail_attributes: [ :detail_category_id, ... ] },
end

Both kind and detail_attributes are being properly set in the first two lines of the create method. However, thing_params.delete(:kind) isn't removing the "kind" key-value pair from the thing_params hash. Same with the :detail_attributes one.

What can I do so they are removed from the thing_params?

Upvotes: 0

Views: 43

Answers (1)

mu is too short
mu is too short

Reputation: 434735

When you call thing_params, you're getting a copy of a bunch of stuff from params. Then you delete :detail_attributes from that copy. Then you call thing_params again to get another fresh copy. You should be doing it more like this:

clean_params = thing_params
detail_attributes = clean_params.delete(:detail_attributes)
#...
@thing = current_user.things.build(clean_params)

That way you'll only be working one copy of the cleaned up params rather than two.

Upvotes: 1

Related Questions