Question

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...

Était-ce utile?

La solution

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.

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top