shou2017.com
JP

How to use the Helper method to branch actions

Sun Jul 30, 2017
Sat Aug 10, 2024

What we want to do

  • On new action, go to the confirmation screen (url: confirm_blogs_path)
  • Go to the list screen on update action (blogs_path)

form_for is the default, and what URL to send is determined by the argument.

  • If the argument does not exist in the record, it is sent to the create action.
  • If the argument exists in the record, send to update action.

To send to the confirm action (confirm action), we need to give an option to change the destination.

So, you can simply edit form_for and give the option url: confirm_blogs_pathurl to make it look like this

<%= form_for(@blog, url: confirm_blogs_path) do |f| %>

This would result in an error when executing the edit action. To avoid this error, create a helper method so that the url: confirm_blogs_path option is generated for the new action and the blogs_path option is generated for the update action.

Create helper method in app/helpers/blogs_helper.rb

module BlogsHelper
  def choose_new_or_edit
    if action_name == 'new' || action_name == 'confirm'
      confirm_blogs_path
    elsif action_name == 'edit'
      blog_path
    end
  end
end

Use helper methods that you define

app/views/blogs/_form.html.erb

<%= form_for(@blog, url: choose_new_or_edit) do |f| %>

Above.

See Also