假设我有一个events
控制器。如果我/events
请求GET
,它将在新闻控制器中以index
操作回复,此视图将显示未来事件。
我想添加一个名为past
的新操作,它类似于index
,它会返回一个Event
的数组,但会有另一个查询。
我已将routes.rb
添加到此块:
resources :events do
collection do
get :past
end
end
我想知道events_controller
:
def history
@events => Event.past
render :template => 'index'
end
但是当我在浏览器中请求http://127.0.0.1:3000/events/past
它不起作用时,会在日志中抛出这些行:
Started GET "/events/past" for 127.0.0.1 at 2012-04-02 19:32:01 -0500
Processing by EventsController#show as HTML
Parameters: {"id"=>"past"}
最后,你有rake routes
输出:
events GET /events(.:format) {:action=>"index", :controller=>"events"}
event GET /events/:id(.:format) {:action=>"show", :controller=>"events"}
past_events GET /events/past(.:format) {:action=>"past", :controller=>"events"}
contact_us_event POST /events/:id/contact_us(.:format) {:action=>"contact_us", :controller=>"events"}
GET /events(.:format) {:action=>"index", :controller=>"events"}
POST /events(.:format) {:action=>"create", :controller=>"events"}
new_event GET /events/new(.:format) {:action=>"new", :controller=>"events"}
edit_event GET /events/:id/edit(.:format) {:action=>"edit", :controller=>"events"}
GET /events/:id(.:format) {:action=>"show", :controller=>"events"}
PUT /events/:id(.:format) {:action=>"update", :controller=>"events"}
DELETE /events/:id(.:format) {:action=>"destroy", :controller=>"events"}
其他测试是使用Rails控制台检查路线:
$ script/rails c
1.9.2-p318 :001 > rs = ActionController::Routing::Routes
1.9.2-p318 :002 > rs.recognize_path "/events/past", :method => :get
=> {:action=>"show", :controller=>"events", :id=>"past"}
怎么了?
答案 0 :(得分:0)
尝试:
resources :events do
get :past, :to => "events#past"
end
我认为您不需要收集上下文。 (你可能不需要:分开)
另一种方法是将事件调用放在资源之上。假设你不需要带它的集合。
get 'events/past', :to => "events#past"
resources :events
应该为您提供正确的路线。
供参考:Rails 3 routes: How to avoid conflict with 'show' action?
答案 1 :(得分:0)
问题在于路由优先级,这里有一个routes.rb
块可用:
resources :events, :only => [:index, :show] do
get 'past', :on => :collection
post 'contact_us', :on => :member
end