[RAILS] Ruby: Account editing function

【Overview】

1. Conclusion </ b>

2. How to code </ b>

3. Development environment </ b>

Supplement </ b>

  1. Conclusion

Code the edit action / update action in the controller, and code the helper method required in edit.html.erb </ b>!
2. How to code

  • We are using devise gem.

config/roites.rb


Rails.application.routes.draw do
  devise_for :users
  root to:'XXXX#index'

  resources :users, only: [:edit, :update] #---❶
end

❶: I want to instruct the users controller only for edit and update actions, so I code only for resources.

app/controllers/users_controller.rb


class UsersController < ApplicationController

  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

end

❶: I want to edit the account (name and email in this case) as set in the routing, so I want to receive the update function command after editing and editing and instruct model, view, so define the action using def doing.

❷: I'm not sure which account I want to update, so I'm doing it for the currently logged-in user. current_user can be used by installing the devise gem.

❸: The top page is returned if the update is successful, and the edit screen is returned if the update is unsuccessful. To briefly explain, it is redirect to because I want to update the user information after it is updated (= I want to overwrite the value of the original instance variable). If it fails, I'm using render because I just need to return to the edit screen without updating the user's incorrect information.

❹: Set the strong parameter to receive data while preventing unintended user edits and updates. I'm using the require method to get information from the user model. If you want to specify the parameters in more detail, use the column name as the key name.

params.require(:Model name).permit(:Column name(Become a key name),・ ・ ・ ・) 

If you use the helper method form_with to send the information of the person who is currently logged in, the simple account editing function is completed.

ruby:app/views/users/edit.html.erb


<%= form_with model: current_user, local: true do |f|%>
 <%= f.text_field :name %>
 <%= f.email_field :email  %>
 <%= f.submit "update"%>
<% end %>

  1. Development environment

Ruby 2.6.5
Rails 6.0.3.3
MySQL 5.6.47 SequelPro 1.1.2
VScode

Supplement

  1. You can use the merge method in ❹ to merge hashes and add information.
params.require(:user).permit(:name, :email).merge(user_id: current_user.id)