How to write a process to extract the contents of strong parameters in Rails
Editing screen ↓ Editing content confirmation screen ↓ Completion screen
For some reason, in the screen transition When you want to display the value of the strong parameter on the edit content confirmation screen, etc.
What are strong parameters? https://qiita.com/ozackiee/items/f100fd51f4839b3fdca8
Ruby:user_edit.html.erb
<!--name and email are submitted from the input form to the confirmation screen-->
<!--It is an edit about the created user, and its ID value shall be passed separately as a URL parameter.-->
<%= form_with(model:@user, url: confirm_user_path) do |f| %>
<div class="field">
<%= f.text_field :name, placeholder: "Enter your username!" %>
</div>
<div class="field">
<%= f.text_field :email, placeholder: "e-Please enter your mail address!" %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
UsersController.php
//Define strong parameters
private
def user_params
params.require(:user).permit(:name, :email)
end
UsersController.php
def edit_confirm
@user = User.find(params[:id]) #Get user data with the ID obtained from the URL parameter(Example: users/3/edit_confirm)
@user.name = user_params[:name] #Extracting the value of a strong parameter & assigning it to a variable
@user.email = user_params[:email] #Same as above
end
Ruby:edit_confirm.html.erb
<h2>Confirmation of edited contents</h2>
<p>Full name:<%= @user.name %>Mr.</p>
<p>mail address:<%= @user.email %></p>
Regarding how to create a "confirmation screen", in Qiita articles etc., it is often
UsersController.erb
@user = User.new(user_params)
And set it on the template side
Ruby:edit_confirm.html.erb
<h2>Confirmation of edited contents</h2>
<p>Full name:<%= @user.name %>Mr.</p>
<p>mail address:<%= @user.email %></p>
But in my case Because I set a certain validation for the create action When I ran User.new, it was recognized as a create action and I was getting a validation error. I wonder if strong parameters can be used to display the input contents on the confirmation screen while avoiding it. When I tried it, I was able to get it and assign it to a variable by the above method.
I'm glad if you can use it as a reference.
Recommended Posts