使用Rails路由分组类似操作的最佳方法?

时间:2015-03-06 23:21:31

标签: ruby-on-rails ruby-on-rails-3 rails-routing

我希望能够在一个控制器下对类似的操作进行分组,以保持整洁干净。

例如,如果我有Game模型,我目前有:

resources :games do
  get 'schedule/previous', to: "Games#previous"
  get 'schedule/upcoming', to: "Games#upcoming"
  get 'schedule/calendar', to: "Games#calendar"
end

这些显然变得越来越不合适,特别是因为我在GamesController中有很多其他行为。如何将它们移动到新的控制器(或者以更干净的方式组织它们)?

如果可能的话,我想把新的" Schedule" app/controllers/games/schedule_controller.rb下的控制器或类似的东西。

我尝试使用命名空间,范​​围和资源(以及其中两个的大多数组合)来做到这一点,并且无法弄明白。

1 个答案:

答案 0 :(得分:1)

根据需要实现此目的

首先修改路线

的routes.rb

resources :games do
  get 'schedule/previous', to: "games/schedule#previous"
  get 'schedule/upcoming', to: "games/schedule#upcoming"
  get 'schedule/calendar', to: "games/schedule#calendar"
end

应用程序/控制器/游戏/ schedule_controller.rb

class Games::ScheduleController < ApplicationController
  #Metods here
  def previous
  end

end

如果您使用rails 4,另一个选择是使用问题。没有必要修改routes.rb

应用程序/控制器/关切/ schedule.rb

module Schedule
  extend ActiveSupport::Concern
  #Metods here
  def previous
  end
end

应用程序/控制器/ games_controller.rb

class GamesController < ApplicationController
  include Schedule
end
相关问题