Simple Rails form use-case help
I'm trying to make a form on the index page of my web app. Right now, I have a controller called home_controller.rb
and a view called index.html.erb
. Those two handle the "index" of my site right now. I'm also trying to add a form to that page. The contents of index.html.erb
are:
<%= form_tag(query_path, :method => "get") do %>
<%= submit_tag("Go!") %>
<% end %>
However, rails gives me this error when I load the page:
undefined local variable or method `query_path'
Here's what I think I want to happen: I want another action in home_controller.rb
which is called query
(right now the开发者_Python百科 only action in this controller is index
). This query
action is the action that is called from my form when you click "Go!" How do I make this happen? What needs to be there instead of query_path
?
Edit:
I feel like there has to be a simpler answer to this, rather than modify the routes.rb
file. How am I thinking of this routing business incorrectly? In my head, any action on my page should default to the controller for the existing page. So if I'm on my index.html.erb
page, which belongs to my home_controller.rb
, my :action => 'query'
should default look for the action in my home_controller.rb
. Why is this not happening? That's exactly what I want to happen.
Maybe I'm thinking about this the entirely wrong way, which is why we're hacking a solution together. Here's what I want: I want the user to click a button, which causes the app to query an external API, get some JSON, and display the contents of the JSON. In my head, this meant the button goes to another action in my same controller, which queries the external API, and passes the JSON back to display on the exact same page (all of this with Ajax). Am I approaching this problem the wrong way?
It looks like what you need to do is add a route in config/routes.rb. You can view your current route names with rake routes
. An example route is below
# Will create query_path mapping to home.query action
match 'home/query' => 'home#query', :as => :query
Edit
You need to define this explicitly because rails3 does not default to `[controller]/[action]' wildcard mappings. It is not recommended for RESTful controllers. If you would like to enable this functionality again there is an example you can uncomment in routes.rb but it is not recommended.
First, you probably need a post instead of get. The form would be like :
<%= form_tag query_path do %>
... (your form elements here)
<%= submit_tag "Submit" %>
<% end %>
The query_path that you specify is a named route. For your case, you would need sth like that in your routes.rb :
scope :path => '/home', :controller => :home do
post 'query' => :query, :as => 'query'
end
EDIT :
If this is indeed a get method, just add :method => "get" to the form and change the route to :
scope :path => '/home', :controller => :home do
get 'query' => :query, :as => 'query'
end
精彩评论