2011-11-04 27 views
0

有沒有什麼辦法幹掉這些路線。有一種模式給他們:如何幹掉這些路線

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' } 

在此先感謝!

回答

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" 
1

您的文章中的slu different是否與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

+0

如果我不想要使用資源(我計劃添加許多不同於REST的行爲)?我將如何解決默認參數問題':defaults => {:scope =>'...'}' – axsuul