干燥多个模型的重复路线

时间:2010-08-19 11:43:06

标签: ruby-on-rails

我有一些像新闻和下载这样的模型有很多评论:as => :commentable。评论belongs_to:commentable并且是:polymorphic。与评论一样,有订阅。所以我的路线看起来像这样:

resources :news do
  resources :comments do
    post :like, :on => :member
    delete :like, :on => :member
  end
  resources :subscriptions
  ...
end

resources :downloads do
  resources :comments do
    post :like, :on => :member
    delete :like, :on => :member
  end
  resources :subscriptions
  ...
end

...

有没有办法干这个?我尝试过定义

def comment_resources
  resources :comments do
    # ...
  end
  resources :subscriptions
end

然后在routes.rb的顶部,然后调用comment_resources,但它对我来说似乎很脏,因为它没有正确地命名为/在类中。

2 个答案:

答案 0 :(得分:3)

1)如果你在新闻和下载中都有完全相同的内部路线,你可以制作

%w(news downloads).each do |res|
  resources res do
    resources :comments do
      post :like, :on => :member
      delete :like, :on => :member
    end
    resources :subscriptions
    ...
  end
end

2)否则你可以查看https://github.com/rails/routing_concerns(将作为rails-4的一部分包含在内):

concern :commentable do
  resources :comments do
    post :like, :on => :member
    delete :like, :on => :member
  end
  resources :subscriptions
end

resources :news, concerns: :commentable do
  ...
end
resources :downloads, concerns: :commentable do
  ...
end

答案 1 :(得分:0)

你走在正确的轨道上。您可以在routes.draw do / end块中定义方法,以便它不会在全局命名空间中纠结。

Application.routes.draw do
  def comment_resources
    resources :comments do
      post :like, :on => :member
      delete :like, :on => :member
    end
    resources :subscriptions
    ...
  end

  resources :downloads do
    comment_resources
  end

  resources :news do
    comment_resources
  end
end

取自:http://symmetricinfinity.com/2013/04/16/drying-up-your-api-routes-in-rails.html