Adding an action to an existing controller (Ruby on Rails)

独自空忆成欢 提交于 2019-11-28 04:21:09

Your routing isn't set up to allow that route. Assuming you're using the default scaffolding, put this line before the map.resources :posts line in config/routes.rb:

map.connect "posts/:action", :controller => 'posts', :action => /[a-z]+/i

The regex for :action restricts it to just a-z (to avoid catching things like /posts/1). It can be improved if you need underscores or numbers in your new actions.

The error you're making is actually a pretty common one.

Basically, Rails automatically maps URLs for your scaffolds. So when you created the Posts scaffolds, Rails is mapping the URL routes for it. One such route is the URL for viewing a single post: /posts/(post_id)

So, when you're entering the URL /posts/start Rails thinks you're saying "Hey, give me the post with ID = start. So Rails complains that the show method can't find a post with such ID.

One quick way to fix this is to make sure your config/routes.rb has the route for the start action before the scaffolding routes:

# Route for start action
map.connect '/posts/start', :controller => 'posts', :action => 'start'
# Default mapping of routes for the scaffold
map.resources :posts

Anyway, hope that helps.

On Rails 4.x use:

get '/posts/start', :controller => 'posts', :action => 'start'

On Rails 3.x use:

match '/posts/start', :controller => 'posts', :action => 'start'

instead of

map.connect '/posts/start', :controller => 'posts', :action => 'start'

it solved my issue.

Amanuel

Try this if you are using rails 3.0.3

in your route.rb

 resource :posts do
   collection do
     get 'start'
   end
 end

this might help

I want to say, sometimes Rails gets sticky with routes-caching, even in the development environment.

It may help to restart your Rails server. This has worked for me more times than I can count when receiving this error.

chernia

This works:

map.resource :post, :collection => { :my_action => :get}

I found the solution to my problem, in the routes.rb file where

map.resource :post

I added with collection argument, so it stayed this way:

map.resource :post, :collection => { :my_action => :get}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!