How to remove a field from params[:something]

后端 未结 5 1220
野性不改
野性不改 2020-12-22 20:21

My registration form, which is a form for the Users model, takes a string value for company. However, I have just made a change such that users belongs_to companies. Therefo

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-22 21:17

    Rails 4/5 - edited answer (see comments)

    Since this question was written newer versions of Rails have added the extract! and except eg:

    new_params = params.except[the one I wish to remove]
    

    This is a safer way to 'grab' all the params you need into a copy WITHOUT destroying the original passed in params (which is NOT a good thing to do as it will make debugging and maintenance of your code very hard over time).

    Or you could just pass directly without copying eg:

    @person.update(params[:person].except(:admin))
    

    The extract! (has the ! bang operator) will modify the original so use with more care!

    Original Answer

    You can remove a key/value pair from a Hash using Hash#delete:

    params.delete :company
    

    If it's contained in params[:user], then you'd use this:

    params[:user].delete :company
    

提交回复
热议问题