How to remove a field from params[:something]

后端 未结 5 1206
野性不改
野性不改 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 20:58

    To be possible to delete you can do a memo:

    def parameters
      @parameters ||= params.require(:root).permit(:foo, :bar)
    end
    

    Now you can do:

    parameteres.delete(:bar)
    
    parameters
    => <ActionController::Parameters {"foo" => "foo"} permitted: true>
    
    0 讨论(0)
  • 2020-12-22 21:03

    The correct way to achieve this is using strong_params

    class UsersController < ApplicationController
      def create
        @user = User.new(user_params)
      end
    
      private
    
      def user_params
        params.require(:user).permit(:name, :age)
      end
    end
    

    This way you have more control over which params should be passed to model

    0 讨论(0)
  • 2020-12-22 21:03
    respond_to do |format|
      if params[:company].present?
        format.html { redirect_to(:controller => :shopping, :action => :index) }
      else
        format.html
      end
    end
    

    this will remove params from the url

    0 讨论(0)
  • 2020-12-22 21:04

    You should probably be using hash.except

    class MyController < ApplicationController
      def explore_session_params
        params[:explore_session].except(:account_id, :creator)
      end
    end
    

    It accomplishes 2 things: allows you to exclude more than 1 key at a time, and doesn't modify the original hash.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题