[Ruby] TECH CAMP learning personal application creation ③

1 minute read

Addition of user information editing function

First, enter the following code at the terminal.

terminal.


$ rails g controller users

Then enter the following in the routing.

routes.rb


 devise_for :users
 root "photos#index"
 resources :users, only: [:edit, :update]

The meaning of resources means resources in Japanese, and I think it can be interpreted as using the editing and updating functions in users.

Then edit the controller.

users_controller.rb


def edit
end

def update
   if current_user.update(user_params)
      redirect_to root_path
   else
      render :edit
   end
end

private

def user_params
   params.require(:user).permit(:name, :email)
end

(1) current_user is a helper method of devise, and you can get the user information during login.
(2) redirect_to transfers to a path different from the originally received path. The above means forwarding to root_path.
③ If the above fails, render will call edit.
④ private is a private method that cannot be called from outside the class.
The merit
-Isolate methods that are in trouble if called from outside the class
-Readability, when searching for a method called from outside the class, you do not have to read the part below private.
(5) user_params The following are strong parameters that receive only parameters with the specified key.
⑥ Request user in the strong parameter to get permission for: name ,: email. Use binding.pry immediately after update to see the details.