0

I have a simple Rails app in which a user submits an integer in a form_tag form, a Ruby script finds the prime factors of the integer, and the output is displayed in a new view. How can I make it so that the output is displayed in the same view as the form instead of a new one?

Here's my current code:

routes.rb:

  match '/primes', to: 'programs#primes'
  post '/factors', to: 'programs#factors'

primes.html.erb:

  <%= form_tag('/factors') do %>
  <div class="field">
   <p>Enter an integer greater than 1:</p>
   <p><%= text_field_tag :number %></p>
  </div>
  <div class="actions">
   <p><%= submit_tag("Find factors") %></p>
  </div>
  <% end %>

programs_controller.rb:

  def factors
    n = Integer(params[:number])
    .
    .
    .
    # script finds prime factors, stores output in @output
  end

factors.html.erb:

  <%= @output %>

So what I want the app to do is to render @output in '/primes' instead of routing to '/factors'.

1
  • You can do one thing, that submit your form to the same page and use a flag on the submission of the form, and show the output according to the flag value is set or reset. you can use javascript if you find its need. Commented Feb 27, 2013 at 5:43

1 Answer 1

1

You can tell the factors controller action to use the same view as the primes controller action like so:

def factors
  # script finds prime factors, stores output in @output
  render :action => 'primes'
end

You also need to move <%= @output %> to primes.html.erb for it to show up there

Sign up to request clarification or add additional context in comments.

1 Comment

Got it! I had tried render :action, but I was putting it in the wrong place. Thanks for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.