如何干掉这些路线

时间:2011-11-04 05:46:41

标签: ruby-on-rails ruby

有没有办法干掉这些路线。他们有一种模式:

get "articles/new" => "articles#new", :as => :new_article
post "articles/new" => "articles#create", :as => :create_article
get "articles/:slug/edit" => "articles#edit", :as => :edit_article

get "stores/:id/articles/new" => "articles#new", :as => :new_store_article, :defaults => { :scope => 'store' }
post "stores/:id/articles/new" => "articles#create", :as => :create_store_article, :defaults => { :scope => 'store' }
get "stores/:id/articles/:slug/edit" => "articles#edit", :as => :edit_store_article, :defaults => { :scope => 'store' }

get "warehouses/:id/articles/new" => "articles#new", :as => :new_warehouse_article, :defaults => { :scope => 'warehouse' }
post "warehouses/:id/articles/new" => "articles#create", :as => :create_warehouse_article, :defaults => { :scope => 'warehouse' }
get "warehouses/:id/articles/:slug/edit" => "articles#edit", :as => :edit_warehouse_article, :defaults => { :scope => 'warehouse' }

提前致谢!

2 个答案:

答案 0 :(得分:1)

文章中的slug与article_id不同吗?尝试将以下内容添加到您的文章模型中:

#This overrides the :id in your routes, and uses the slug instead
def to_param
  slug
end

然后,以下内容适用于您的路线。

resources :articles, :only => [:new, :create, :edit]
scope :stores do
  resources :articles, :only => [:new, :create, :edit]
end
scope :warehouses
  resources :articles, :only => [:new, :create, :edit]
end

我强烈建议您阅读http://guides.rubyonrails.org/routing.html

答案 1 :(得分:0)

我想要一个优雅的解决方案,我似乎找到了一个。基本上,添加一个我可以在我的路径文件中使用的辅助方法,方法是将其放在lib/routes_helper.rb中:

class ActionDispatch::Routing::Mapper
  def article_resources_for(scope = nil)
    scope_path_symbol = scope_path = nil
    defaults = {}

    unless scope.blank?
      scope_path = "#{scope}/:id/"
      scope_path_symbol = "#{scope}_"
      defaults = { :defaults => { :scope => scope } }

    get "#{scope_path}articles/new" => "articles#new", { :as => :"new_#{scope_path_symbol}article" }.merge(defaults)
    post "#{scope_path}articles/new" => "articles#create", { :as => :"create_#{scope_path_symbol}article" }.merge(defaults)
    get "#{scope_path}articles/:slug/edit" => "articles#edit", { :as => :"edit_#{scope_path_symbol}article" }.merge(defaults)

  end
end

然后在我的routes.rb文件中,我可以简单地执行

article_resources_for
article_resources_for "stores"
article_resources_for "warehouses"