简体   繁体   中英

Ruby on Rails - Two different Edit pages and forms. How to?

Well I need 2 pages. One to edit some information and other to just edit the password of the user.

I have the first working already and ignoring the password check. code below:

Controller:

def edit
    @user = User.find(params[:id])
    @role = @user.role
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      #sucesso
      flash[:success] = "Dados Editados com sucesso!"
      redirect_to "/user_home/#{@user.id}"
    else
      render 'edit'
    end
  end

Model:

validates :password, length: { minimum: 6 }, on: :create
  validates :password, length: { minimum: 6 }, on: :update, allow_blank: true;

Now how can i implement a second edit just for the password? new routes? new views?

Can someone help me?

One idea is to show passwords in your edit form also because you are allowing blank submit of the attributes so they are updated only when present.

You also didn't specify if you are using gem "devise" because that changes what i wrote below.


If you really want to do the second view here is some help:

In routes.rb you need a new route to show the form with just passwords.

resources :users do
  member do
    get :edit_password
    put :update_password
  end
end

In your users_controller.rb add the following method:

def edit_password
  @user = User.find(params[:id])
end

def update_password
  user = User.find(params[:id])
  # also in here i'm calling the authenticate method that usually is present in bcrypt.
  if user and user.authenticate(params[:old_password])
    if params[:password] == params[:password_confirmation]
      user.password = BCrypt::Password.create(params[:password])
      if user.save!
        redirect_to edit_password_url, notice: "Password changed"
      end
    else
        redirect_to edit_password_url, notice: "Incorrect Password."
    end
  else
    redirect_to edit_password_url, notice: "Incorrect Password."
  end
end

NOTE: in the update_password method i'm using authenticate that is present in bcrypt gem. It's recommended to use that. Read more here: http://api.rubyonrails.org/classes/ActiveModel/SecurePassword/ClassMethods.html

# in Gemfile
gem 'bcrypt', '~> 3.1.7'

Create a new file views/users/edit_password.html.erb and add the following code:

<%= form_for @user, url: update_password_user_path(@user) do |f| %>
  <%= f.label :old_password %>
  <%= f.password_field :old_password %>
  <%= f.label :password %>
  <%= f.password_field :password %>
  <%= f.label :password_confirmation %>
  <%= f.password_field :password_confirmation %>
  <%= f.submit "Update password" %>
<% end %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM