Blake
Blake

Reputation: 109

Posting a variable to another controller

I have a welcome controller/view.

On the index.html.erb I have a simple form that takes in one value:

<%= form_tag do %>
<div>
<%= label_tag(:zip, "Enter Zipcode to search in:") %>
  <%= text_field_tag(:zip) %>
 </div>
  <%= submit_tag("Search") %>
<% end %>

Upon hitting the submit button I'd like to pass the zip variable to another controller called "theaters". The variable doesnt need to be saved in any kind of model, its just being used to execute an API call in the Theaters controller.

Whats the simplest way to do this?

Thanks

Upvotes: 2

Views: 53

Answers (2)

Mandeep
Mandeep

Reputation: 9173

Make a route for your method in TheatresController, lets assume your method name is get_zip

post '/get_zip' => 'theaters#get_zip', as: "zip"

Create your form

<%= form_tag(url: zip_path, method: :post) do %>
  <div>
    <%= label_tag(:zip, "Enter Zipcode to search in:") %>
    <%= text_field_tag(:zip) %>
  </div>
  <%= submit_tag("Search") %>
<% end %>

Access it inside your method:

def get_zip
  @zip = params[:zip]
  #your logic
end

Upvotes: 0

Mark
Mark

Reputation: 6404

Try this:

<%= form_tag({controller: "theaters", action: "index"}) do %>
<div>
    <%= label_tag(:zip, "Enter Zipcode to search in:") %>
    <%= text_field_tag(:zip) %>
</div>
<%= submit_tag("Search") %>
<% end %>

Hope it helps.

Upvotes: 2

Related Questions