Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a custom action to the controller in Rails 3

Tags:

I want to add another action to my controller, and I can't figure out how.

I found this on RailsCasts, and on most StackOverflow topics:

# routes.rb resources :items, :collection => {:schedule => :post, :save_scheduling => :put}  # items_controller.rb   ...   def schedule   end    def save_scheduling   end  # items index view: <%= link_to 'Schedule', schedule_item_path(item) %> 

But it gives me the error:

undefined method `schedule_item_path' for #<#<Class:0x6287b50>:0x62730c0> 

Not sure where I should go from here.

like image 703
user1885058 Avatar asked Dec 07 '12 13:12

user1885058


People also ask

What does Before_action do in Rails?

When writing controllers in Ruby on rails, using before_action (used to be called before_filter in earlier versions) is your bread-and-butter for structuring your business logic in a useful way. It's what you want to use to "prepare" the data necessary before the action executes.

How should you use filters in controllers?

Filters are inherited, so if you set a filter on ApplicationController , it will be run on every controller in your application. The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a "before" filter renders or redirects, the action will not run.

What does a controller do in Rails?

The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services. It is responsible for routing external requests to internal actions.


1 Answers

A nicer way to write

resources :items, :collection => {:schedule => :post, :save_scheduling => :put} 

is

resources :items do   collection do     post :schedule     put :save_scheduling   end end 

This is going to create URLs like

  • /items/schedule
  • /items/save_scheduling

Because you're passing an item into your schedule_... route method, you likely want member routes instead of collection routes.

resources :items do   member do     post :schedule     put :save_scheduling   end end 

This is going to create URLs like

  • /items/:id/schedule
  • /items/:id/save_scheduling

Now a route method schedule_item_path accepting an Item instance will be available. The final issue is, your link_to as it stands is going to generate a GET request, not a POST request as your route requires. You need to specify this as a :method option.

link_to("Title here", schedule_item_path(item), method: :post, ...) 

Recommended Reading: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

like image 85
deefour Avatar answered Oct 11 '22 23:10

deefour