Rails 3路线:DRY会员

时间:2010-11-24 02:31:52

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

我需要将以下成员方法添加到多个资源中,有没有办法干掉它?

 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

1 个答案:

答案 0 :(得分:7)

你不能只在路线文件中定义一个方法吗?

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