0

Let's say I have two models (Model1 and Model2) that share the same controller, both have many instances of Model3.

How can I achieve to nest Model 3 within both models and have the route: model_3_path(@model) instead of model_1_model_3_path(@model) and model_2_model_3_path(@model)

I want my model_3_path(@model) function to look like this:

def model_3_path(model)
  if model.is_a? Model1
    "/model1/#{model.id}/model3"
  elsif model.is_a? Model2
    "/model2/#{model.id}/model3"
  end
end

My current progress:

concern :three { resources :model3, shallow: true }
resources :model1, concerns: :three
resources :model2, concerns: :three, controller: :model1, except: [:index] # /model2 isn't permitted

I can't seem to find the right approach...

Danyel
  • 2,180
  • 18
  • 32

2 Answers2

0

I found a simple solution: First, I removed the shallow in model3.By opening the helper class and adding a method_missing definition, this was easily possible:

def method_missing(method, *args, &block)
  super unless /model3s?_(path|url|uri)$/ =~ method.to_s
  sub_string = nil
  if args.first.is_a? Model1
    substring = 'model1'
  elsif args.first.is_a? Model2
    substring = 'model2'
  end
  self.send(method.to_s.gsub('model3', "#{substring}_model3"), *args, &block)
end

It would be possible to define each of those by themselves (new_model3_path, model3_path, edit_model3_path, model3s_path) but I found this one more concise.

Danyel
  • 2,180
  • 18
  • 32
-1

If you want to have a path which does not specify it's parent just have it as a top level route, not a concern.

MatthewFord
  • 2,918
  • 2
  • 21
  • 32
  • I do want them to specify their parents, I only want the named route to be generic, depending on the parameter that comes in which can be either of Model1 or of Model2. Please read the question more carefully. – Danyel Jun 27 '13 at 10:47