boated_tw
boated_tw

Reputation: 424

Using form_tag without redirect to new page

Since there are more than one submit_tag in the same form, I used send(params[:commit]) in order to pass submit_tag value to desired actions {action2, action3}.

An issue here is, I want to call an action using form_tag without redirect to the new action page. So far, I knew that inserting remote: true into form_tag can deal with this issue but it's necessary to do a more code (AJAX) for calling an action2 or action3.

I'm wondering, is there any possible way to call form_tag without redirecting to action1.html.erb but send(params[:commit]) can be used.

In page.html.erb

<%= form_tag "action1" do %>
  <%= text_area_tag :data %>
  <%= submit_tag: action2, remote: true %>
  <%= submit_tag: action3, remote: true %>
<% end %>

In controller.rb

def action1
   send(params[:commit].downcase)
end

def action2
  puts params[:data]
  ...
end

def action3
  puts params[:data]
  ...
end

Upvotes: 0

Views: 315

Answers (2)

Josh Brody
Josh Brody

Reputation: 5363

Could just do this:

class PersonController < ApplicationController

  def action1
    send(parse_action)
    # ...
  end

  def action2
    process_action2
    # ...
  end

  def action3
    process_action3
    # ...
  end

  protected

  def parse_action
    %w{action2 action3}.include?(params[:commit]) ? params[:commit] : 'action2'
  end

  def process_action2
    # do stuff
  end

  def process_action3
    # ... 
  end
end

Upvotes: 0

Jeremie
Jeremie

Reputation: 2411

I would simply use a case statement and deal with the return value of action 2 or 3. Maybe something like this:

def action1
  case params[:commit].downcase
  when action2
    result = action2(params)
  when action3
    result = action3(params)
  end
  # do something with result now
  render result
end

I will also move the two actions to private inside the controller.

This accomplish what you want to do and avoid strings evaluation.

I hope this helps

Upvotes: 0

Related Questions