Ross R
Ross R

Reputation: 389

Rails 3, Form submitting to its controller

I'm new to Rails and I've just spent another hour Googling and not finding an example.

So I have a simple form that I need to submit to an API. So I tried submitting it to the API directly but got advice that I do it in my app so I can do something with the results. Anyway, here's my simple form:

<%= form_tag(:action => 'submit') do |f| %>
<%= f.text_field :email, :value => "Your email address...", :class => "text", :id => "email", :name => 'email',
        :onFocus => "change(this,'#222222'); this.value=''; this.onfocus=null;",
                :size => "26" %>
<%= f.hidden_field :ref_code, :id => 'ref_code', :name => 'ref_code', :value => @referralid %>
<%= submit_tag "Enter To Win", :class => "button-positive submit" %>
<% end %>

Everything I'm seeing has forms that that use a model, I have no need to persist this data, just pass it on to the API.

So my thought was I just create an action in the home controller, where this page lives and have the action submit to it but I get a RoutingError and it's: No route matches {:action=>"submit", :controller=>"home"}

So what do I need to put in the Routes.rb? I tried:

namespace :home do 
  resources :submit 
end

No Joy... I'm sure it's simple but I just can't find the right example.

Upvotes: 2

Views: 10060

Answers (1)

ecoologic
ecoologic

Reputation: 10420

I think that you should have a look at the ruby guides, it's very well explained (but I don't think it talks about API) and it will save you a lot of time in the future, I swear.

Not sure what you mean but I see some wired stuff, so I hope to be useful, but if you're following some tutorials from the net let us know the link.

Basically what I do is always to call an action of a controller (MVC), following this way you should have a controller (?? apis_controller ??) and call one action of it.

So you want to use form_tag instead of form_for because you're not addressing a model, therefor you want to get rid of f. and use suffix _tag (api).

<%= form_tag(send_api_path) do %>
<%= text_field_tag :email, "Your email address..." %>
<%= hidden_field_tag :ref_code,  @referralid %>
<%= hidden_field_tag :api_name, 'your_api_name' %>
<%= submit_tag "Enter To Win" %>
<% end %>

Then, in your apis_controller.rb you create an action send where you send and manage your request.

#apis_controller.rb
def send
  # TODO: your code here
end

Another thing is to set the routes, something like

#routes.rb
  match 'apis/send' => 'apis#send', :as => :send_api

I'm sure this is not 100% working code, but it should be useful

How to call the api? I had I fast look and found this.

When you ask for help it's always good to attach the error you get, this makes it easier for people to understand the problem.

Upvotes: 10

Related Questions