Ruby on rails 允许POST到几个端点和所有方法到其余端点的Rails路由?

Ruby on rails 允许POST到几个端点和所有方法到其余端点的Rails路由?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有一个Rails控制器,大约有60多个动作。我需要将其更改为只允许对大约20个操作发布请求,并允许对其余操作使用任何请求方法 有没有办法做到这一点,这样我就不必手动指定所有路线都允许的路线? 这就是我迄今为止所拥有的(和工作): 我试着创建这样的东西,但它只会导致路由错误 post_regex = /first_route|second_route/ class AllRoutesConstraint def self.matches?(request) (request.quer

我有一个Rails控制器,大约有60多个动作。我需要将其更改为只允许对大约20个操作发布请求,并允许对其余操作使用任何请求方法

有没有办法做到这一点,这样我就不必手动指定所有路线都允许的路线?

这就是我迄今为止所拥有的(和工作):

我试着创建这样的东西,但它只会导致路由错误

post_regex = /first_route|second_route/
class AllRoutesConstraint
  def self.matches?(request)
    (request.query_parameters[:action] !~ post_regex)
  end
end
map.connect '/myroute/:id/:action', :controller => 'my_controller', :constraints => {:action => post_regex }, :conditions => { :method => :post }
map.connect '/myroute/:id/:action', :controller => 'my_controller', :constraints => {:action => AllRoutesConstraint }

如果您愿意在控制器中而不是在routes.rb中执行此操作,那么它应该非常简单。让所有请求类型通过路由文件:

# in config/routes.rb
map.connect '/myroute/:id/:action', :controller => 'my_controller'
然后,在控制器中筛选仅POST操作

# in app/controllers/my_controller.rb
POST_ONLY_ACTIONS = [:first_route, :second_route]

before_filter :must_be_post, :only => POST_ONLY_ACTIONS

# your actions...

protected

def must_be_post
  unless request.method == "POST"
    raise ActionController::MethodNotAllowed.new("Only post requests are allowed.")
  end
end
如果在routes.rb中设置该方法,Rails将为您生成相同的错误和错误消息


缺点是您的routes.rb文件不再是允许哪些请求的唯一权威来源。但是,由于您试图从routes文件中删除某些信息(非POST请求列表),您可能会发现这种折衷是可以接受的。

如果您愿意在controller中而不是routes.rb中执行此操作,那么应该非常简单。让所有请求类型通过路由文件:

# in config/routes.rb
map.connect '/myroute/:id/:action', :controller => 'my_controller'
然后,在控制器中筛选仅POST操作

# in app/controllers/my_controller.rb
POST_ONLY_ACTIONS = [:first_route, :second_route]

before_filter :must_be_post, :only => POST_ONLY_ACTIONS

# your actions...

protected

def must_be_post
  unless request.method == "POST"
    raise ActionController::MethodNotAllowed.new("Only post requests are allowed.")
  end
end
如果在routes.rb中设置该方法,Rails将为您生成相同的错误和错误消息

缺点是您的routes.rb文件不再是允许哪些请求的唯一权威来源。但是,由于您试图从路由文件中删除一些信息(非POST请求列表),因此您可能会发现这种折衷是可以接受的