Alexandre Butynski
Alexandre Butynski

Reputation: 6746

How to override/alias named route helpers in Rails

In my application, all of my models depend on a main model. That's why all of my routes are nested inside this main route. My route.rb look like that :

resources :main_model do
  resources :model_1
  resources :model_2
  resources :model_3 do
    resources :model_4
  end
end

So, any of my named route helpers repeat the same beginning with the same object (wich is in session). I call my paths like that :

new_main_model_model_1_path(session[:main_model])
edit_main_model_model_3_model_4_path(session[:main_model], @model_3, @model_4)

But i am tired of repeating myself in each link so I want to be able to call my routes like that :

new_model_1_path()
edit_model_3_model_4_path(@model_3, @model_4)

I could write alias methods...

def new_model_1_path(model_1)
  new_main_model_model_1_path(session[:main_model], model_1)
end

...but it would not be serious. Is there a way to do it cleanly ? Perhaps by overridding the named route generator ?

Upvotes: 3

Views: 1193

Answers (1)

Lachlan Cotter
Lachlan Cotter

Reputation: 1889

Since you already have reference to your main model in the session you don't actually the routes to identify it. You already know where to find it. So, for the purposes of routing, there's no need to nest the resources at all.

You could use scope instead, if you still want to prefix your routes:

scope "main_model" do
  resources :model_1
  resources :model_2
  resources :model_3 do
    resources: :model_4
  end
end

That will give you the helper methods you want that don't require you to pass the redundant reference to main_model.

Or just don't nest them.

Upvotes: 1

Related Questions