覆盖Rails路由资源方法创建额外的RESTful操作

时间:2016-05-06 06:38:32

标签: ruby-on-rails-4 actiondispatch

在routes.rb中:

  namespace :admin, :format => false do
    resources :activities
    resources :categories
    resources :charities
  end 

在所有map.resources中添加额外的RESTful操作csv_export:

创建initilizer / mapper.rb文件并添加模块ActionDispatch :: Routing :: Mapper :: Resources

module ActionDispatch::Routing::Mapper::Resources
  # Add csv_export to all resources as default action
  def resources(*resources, &block)
    options = resources.extract_options!.dup

    if apply_common_behavior_for(:resources, resources, options, &block)
      return self
    end

    resource_scope(:resources, Resource.new(resources.pop, options)) do
      yield if block_given?

      concerns(options[:concerns]) if options[:concerns]
      collection do
        get :csv_export ,defaults: { format: 'csv' } if   @scope[:path].include?("/admin")
        get  :index if parent_resource.actions.include?(:index)
        post :create if parent_resource.actions.include?(:create)
      end

      new do
        get :new
      end if parent_resource.actions.include?(:new)

      set_member_mappings_for_resource
    end

    self
  end
end

0 个答案:

没有答案