Rails 3 new method route
I created a scaffold class, now i want to add another method in the controller to it and provide a button link to it to call the method.
How do i do this.
Say the method is called 'new_method', what do i put in the erb and routes files in order to call this get method?开发者_运维技巧
Suppose your scaffold class is called Post
, then in your routes you should have:
resources :posts
You then want to add a new_method
, you have to choose whether this will work on the collection
or on a single object.
On a collection
In your routes you write
resources :posts do
collection do
get :new_method
end
end
And in your erb
you would write
<%= link_to 'Do new-method', new_method_posts_path %>
Note, if you want to you could also use button_to
instead of link_to
if you prefer to have a button instead.
On a single object (member)
In your routes you write
resources :posts do
member do
get :new_method
end
end
And in your erb
you would write
<%= link_to 'Do new-method', new_method_post_path(@post) %>
Hope this helps.
match '/route' => 'controller#method'
It also depends; it may be cleaner to add the route as a collection or single resource. The the links below for further info :)
http://edgeguides.rubyonrails.org/routing.html
http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/
For example, if you wanted a new routine /filtered
, you have two options.
match '/filtered' => 'products#filtered'
In the erb you'd then use filtered_path
as link_to
's action/path parameter.
You could also add it to the product resource mapping.
resources :products do
collection do
get 'filtered'
end
end
Or:
resources :products do
get 'filtered', :on => :collection
end
Either will provide a new path (the names of all your paths are viewable by running the rake routes
task) called filtered_products_path
.
Please see http://guides.rubyonrails.org/routing.html#adding-more-restful-actions this will direct you to the solution.
Lets call the controller HomeController for this answer. Lets create a view file called new_method.html.erb
. In the routes.rb create a route like this:
match 'new_method' => 'home#new_method'
I hope this will work.
精彩评论