2

I've got routes setup like the following:

resources :projects do
  resources :project_factors, as: factors
end

I like having the as: :factors so the route becomes:

project_factor_path(@project, @project_factor)

instead of

project_project_factor_path(@project, @project_factor) 

but I'm having trouble getting form_for to generate the correct route.

form_for [@project, @project_factor] fails (as expected) because it tries to use project_project_factor_path, so I tried:

form_for [@project, @project_factor], as: :factor

but this fails with exactly the same error.

Is there a way to get rails to generate the correct path here without explicitly setting the correct url parameter for the create and update case?

Jared
  • 2,885
  • 2
  • 28
  • 31
  • This previous question: http://stackoverflow.com/questions/10906793/how-to-generate-the-proper-url-for-a-nested-resource seems to indicate that if you're using a namespace on the classname it might be interfering with auto-generating your route from the object... have you named your project factors class something like: `Project::ProjectFactor` ??? – Taryn East Feb 07 '17 at 23:31
  • No, just named ProjectFactor: `class ProjectFactor < Factor` – Jared Feb 08 '17 at 00:32

1 Answers1

0

Not ideal, but you can pass in the path separately to the objects eg something like:

form_for [@project, @project_factor], :url => project_factor_path(@project, @project_factor)

(Note: not tested)

It feels a bit redundant to me though... which is exactly what you were trying to reduce, so probably not a good solution for you :P

An alternative might be just to rename your project_factor model to factor. You can still give the database table name as project_factors (use self.table_name = 'project_factors' in the class for Rails to find it).

To me, project/project_factors feels a bit like smurf-typing... ;) YMMV

Taryn East
  • 27,486
  • 9
  • 86
  • 108
  • 1
    Yeah, like I mentioned, explicitly setting the url is what I'm trying to avoid since then I have to have a condition on the form for if the record is saved or not. Renaming the model isn't really an option here, ProjectFactor already inherits from Factor. My question is really why `as` in form_for is having no effect on the generated url. – Jared Feb 08 '17 at 00:30
  • yeah... and I agree it's a good question (to which I do not know the answer)... might be worth delving into the source code for `url_for` (though it's likely to be a rabbit warren) – Taryn East Feb 08 '17 at 00:40