0

From what I understand...

  • If you have a form_for @model, params[:model] is available when the form is submitted. Furthermore, if the form has 2 attributes attr1 and attr2, params[:model][:attr1] and params[:model][:attr2] are available when the form is submitted.
  • In Rails 4, you're supposed to write a method model_params that says params.require(:model).permit(:attr1, :attr2).
  • You'd then use model_params like so: Model.new(model_params).

However, what do you do if you only need one of the fields from the form? Like if you only needed params[:model][:attr1]?

Example:

def create
  @user = User.new(user_params)
  if @user.save
    # need access to params[:user][:password] here
    redirect_to root_url, :notice => "Signed up!"
  else
    render :new
  end
end

private

    def user_params
        params.require(:user).permit(:email, :password, :password_confirmation)
    end
Adam Zerner
  • 17,797
  • 15
  • 90
  • 156

1 Answers1

1

The gem responsible for this behaviour is strong_parameters. The permit() method decides what to pass on to the model based on the attributes you pass to it.

In your case, you passed it :attr1 and :attr2:

params.require(:model).permit(:attr1, :attr2)

This means the model will have attr1 and attr2 set to whatever values were passed from the form.

If you only wanted to set attr1, just remove attr2 from the permit() call.

params.require(:model).permit(:attr1)

You model will not have attr1 set, but not attr2. It's that simple.

You can even permit everything (not recommended) by calling permit! with a bang and no arguments.

You can read more about this behaviour on the gem's Github project page.

Update based on the OP's edit

If you need access to params[:user][:password] in the controller... well, you just accessed it in your example. You accessed it by typing params[:user][:password].

Nothing prevents you from accessing the params hash directly. strong_parameter's job is to prevent you from mass assigning a hash to a model, that's all.

Mohamad
  • 34,731
  • 32
  • 140
  • 219