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.
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.
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.
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.
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_schedulingBecause 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_schedulingNow 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With