ruby-on-rails – Rails 3路由:DRY成员

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails 3路由:DRY成员前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要将以下成员方法添加到许多资源中,有没有办法干掉它?
member do
    get   :votes
    post  :up_vote
    post  :down_vote
  end

在我的routes.rb

resources :news do
  resources :comments do
     member do
        get   :votes
        post  :up_vote
        post  :down_vote
      end
  end
end

resources :downloads do
  resources :whatever do
     member do
        get   :votes
        post  :up_vote
        post  :down_vote
      end
  end
end

编辑

我实际上把它移到了一个像这样的模块中:

module Votable
  module RoutingMethods
    def votable_resources
      member do
        get   "up_votes"
        get   "down_votes"
        post  "up_vote"
        post  "down_vote"
      end
    end
  end # RoutingMethods
end

现在,我的routes.rb看起来像这样:

require 'votable'

include Votable::RoutingMethods

MyApp::Application.routes.draw do

  namespace :main,:path => "/" do
    resources :users do 
      resources :comments do
        votable_resources
      end
    end
  end

end

请参阅我的内联注释,但我希望命名路由看起来像:main_users_comments_up_votes

解决方法

你不能只在路线文件中定义一个方法吗?
def foo
  member do
   get   :votes
   post  :up_vote
   post  :down_vote
  end
end


resources :news do
 resources :comments do
   foo
 end
end

编辑

我之前没有使用过这种技术.当我做“耙路线”时,它似乎工作.无论如何,routes文件只是Ruby代码.请注意您定义的方法名称,因为它是在ActionDispatch :: Routing :: Mapper的实例中定义的.

# routes.rb

MyApp::Application.routes.draw do
  puts self
  puts y self.methods.sort
end

# Terminal
> rake routes

猜你在找的Ruby相关文章