form_for with namespace nested ressources

2019-09-15 05:40发布

问题:

I'm getting the following error in my view with form_for when I use the path edit_projects_proj_paquet_mesures_proj_mesure_path() :

undefined method `projects_proj_mesure_path' for #<#<Class:0xac942e4>:0xac9d1f0>

This error doesn't occur when I use the path new_projects_proj_paquet_mesures_proj_mesure_path().

Though I defined my ressource as nested with a namespace in my config/route.rb

namespace :projects do
    resources :proj_paquets_mesures do
      resources :proj_mesures
    end
end

As recommended in this stackoverflow question-answer, my _form.html.haml begin with :

form_for([:projects, @proj_paquet_mesures, @proj_mesure], :html => {:class => "formulaire-standard"}) do |f|
...

Be aware an exception has been set within config/initializer/inflection.rb :

 ActiveSupport::Inflector.inflections do |inflect|
    inflect.irregular 'proj_paquet_mesures', 'proj_paquets_mesures'
 end

Everything was working fine when I was using Shallow option for my ressources, and using the path projects_proj_mesure_path() :

namespace :projects do
    resources :proj_paquets_mesures, :shallow => true do
      resources :proj_mesures
    end
end

回答1:

Disregard ! This is not a bug.

I solved the issue. The origine of the issue was in the controller :

I wasn't instancing correctly @proj_paquet_mesures. Instead it was holding 'nil' value.

This results in form_for behaving like if I called it with :

form_for (:projects, @proj_mesure) do |f|

and the resulting HTML was :

<form id="edit_proj_mesure_1" class="formulaire-standard" method="post" action="/projects/proj_mesures/1" accept-charset="UTF-8">

So to correct the issue, I just had to modify my controller with :

  def edit
    @proj_paquet_mesures = ProjPaquetMesures.find_by_id(params[:proj_paquet_mesures_id])

    unless @proj_paquet_mesures.nil? then
      @proj_mesure = ProjMesure.find_by_id(params[:id])

      unless @proj_mesure.nil? then
        respond_with(:projects, @proj_mesure)
      else
        render 'blank_page'
      end

    else
      render 'blank_page'
    end
  end

This is working perfectly :

form_for([:projects, @proj_paquet_mesures, @proj_mesure], :html => {:class => "formulaire-standard"}) do |f|