Ruby on Rails5 Posted in the output of the quick learning practice guide. This time, I will post about the function to display a confirmation screen such as "Register with this content" before registering the record! As an example, I am creating a task management application.
<!-Edit title and anchor name->
First, create an action in the controller that transitions to the confirmation screen.
app/controller/tasks_controller.rb
def confirm_new
@task = current_user.tasks.new(task_params)
render :new unless @task.valid?
end
This time, to nest in the task, set as follows.
config/routes.rb
resources :tasks do
post :confirm, action: :confirm_new, on: :new
end
This description will generate the URL / tasks/new/confirm
.
First, create a view of the confirmation screen.
app/views/tasks/confirm_new.html.slim
h1 Confirmation of registration details
= form_with model: @task, local: true do |f|
table.table.table-hover
tbody
tr
th= Task.human_attribute_name(:name)
td= @task.name
= f.hidden_field :name
tr
th= Task.human_attribute_name(:description)
td= simple_format(@task.description)
= f.hidden_field :description
= f.submit 'Return', name: 'back', class: 'btn btn-secondary mr-3'
= f.submit 'Registration', class: 'btn btn-primary'
No data has been saved when this screen is displayed. Since data is needed when executing the create method after this, hidden_field keeps the data of the previous screen invisible to the user and passes it.
Next, set the transition destination of the new addition screen to the confirmation screen.
app/views/tasks/new.html.slim
= form_with model: @task, local: true, url: confirm_new_task_path do |f|
.form-group
= f.label :name
= f.text_field :name, class: 'form-control', id: 'task-name'
.form-group
= f.label :description
= f.text_area :description, rows: 5, class: 'form-control', id: 'task_description'
= f.submit "Verification", class: 'btn btn-primary'
We will implement the processing when the back button of the confirmation screen is pressed. "Back" is added to the name attribute of the back button of the confirmation screen created earlier. When this button is pressed, a parameter called params [: back] is sent, so if there are these params, implement it by rendering to the new method.
app/controllers/tasks_controller.rb
def create
@task = current_user.tasks.new(task_params)
if params[:back].present?
render :new
return
end
if @task.save
redirect_to tasks_url
else
render :new
end
end
This completes the implementation of the confirmation screen!
-Ruby on Rails 5 Quick Learning Practice Guide that can be used in the field
Recommended Posts