Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating Strong Params Only

First of all, I believe there must be some people, who already asked this question before but I don't know how can I google this problem. So, if it is duplicate I am sorry.

I am working on a social media site. I have user model, which I use to register users to the site. It validates, name, email, and password when registering.

I use the same model to make users edit their informations, like username.

This is what I have in my update controller:

  def update
    # Find an existing object using form parameters
    @profile = User.find_by_id(current_user.id)
    # Update the object
    if @profile.update_attributes!(settings_profile_params)
      # If save succeeds, redirect to itself
      redirect_to request.referrer
    else
      # If save fails, redisplay the form so user can fix the problems
      render('edit')
    end
  end

  private # user_params is not an action, that is why it is private.
  def settings_profile_params
    params.require(:user).permit(:first_name, :last_name, :username, :school, :program, :website, :information)
  end

The problem is, I only want to update strong parameters that I defined there. But I am getting an exception because of password validation. I don't know why am I getting this exception. How can I set up system to update the values in strong parameter only.

Thank you.

like image 676
cyonder Avatar asked Jan 25 '26 13:01

cyonder


1 Answers

You can achieve this by changing you password validation. You need to add a condition on password validation.

# Password
  validates :password,
            :presence => {:message => 'Password cannot be blank'},
            :length => {:within => 8..99, :message => 'Password length should be within 8 and 99 characters'}
            :if => Proc.new { new_record? || !password.nil? }
like image 78
Muntasim Avatar answered Jan 27 '26 02:01

Muntasim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!