Marina K
Marina K

Reputation: 345

Can't figure out how Rails route helper should look

I am working on an assignment which includes adding a feature to Typo.

rake routes shows:

admin_content    /admin/content                     {:controller=>"admin/content", :action=>"index"}
                 /admin/content(/:action(/:id))     {:action=>nil, :id=>nil, :controller=>"admin/content"}

I need to create a route helper which matches the following RESTful route: /admin/content/edit/:id and an example of url is /admin/content/edit/1

But I can't figure out how to do it. I tried something like admin_content_path(edit,some_article) but it didn't work. (some_article is just an article object)

In routes.rb file:

# some other code

# Admin/XController
%w{advanced cache categories comments content profiles feedback general pages
 resources sidebar textfilters themes trackbacks users settings tags redirects seo post_types }.each do |i|
match "/admin/#{i}", :to => "admin/#{i}#index", :format => false
match "/admin/#{i}(/:action(/:id))", :to => "admin/#{i}", :action => nil, :id => nil, :format => false
end

#some other code

Thanks a lot for your help!

Upvotes: 0

Views: 158

Answers (1)

nathanvda
nathanvda

Reputation: 50057

If you are using RESTful routes, why not use the Rails default routes?

So your routes.rb would look like

namespace :admin do
  resources :content
  resources :advanced
  resources :categories
  resources :comments
  ...
  <etc>
end

This does assume all your controllers are in the folder admin (but from your comment this seems to be the case.

If you do that, you can just use the standard route-helper: edit_admin_content_path.

If you want to do it manually, you should try adding a name to your route. E.g. as follows:

match "/admin/#{i}/:action(/:id)" => "admin/#{i}", :as => "admin_#{i}_with_action"

and then you should do something like

admin_content_with_action(:action => 'edit', :id => whatevvvva)

As a side-note: I really do not like the meta-programming in your config/routes.rb, if for whatever you really find that the default resources are not a right fit, I would advise to use methods instead (as explained here)

So for example in your config/routes.rb you would write:

def add_my_resource(resource_name)
  match "/#{resource_name}", :to => "#{resource_name}#index", :format => false
  match "/#{resource_name}(/:action(/:id))", :to => "#{resource_name}", :as => 'admin_#{resource_name}_with_action", :action => nil, :id => nil, :format => false
end

namespace :admin do
  add_my_resource :content
  add_my_resource :advanced
  add_my_resource :categories
  ...
end  

which imho is much more readable.

But my advice, unless you really-really need to avoid it, would be to use the standard resources since you do not seem to add anything special.

HTH.

Upvotes: 1

Related Questions