【问题标题】:form_for with namespace nested ressources带有命名空间嵌套资源的 form_for
【发布时间】:2013-01-14 19:37:48
【问题描述】:

当我使用路径 edit_projects_proj_paquet_mesures_proj_mesure_path() 时,我的 form_for 视图中出现以下错误:

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

当我使用路径 new_projects_proj_paquet_mesures_proj_mesure_path() 时不会出现此错误。

虽然我将我的资源定义为嵌套在我的 config/route.rb

中的命名空间
namespace :projects do
    resources :proj_paquets_mesures do
      resources :proj_mesures
    end
end

按照stackoverflow question-answer 中的建议,我的 _form.html.haml 以 :

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

请注意在 config/initializer/inflection.rb 中设置了异常:

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

当我对资源使用 Shallow 选项并使用路径 projects_proj_mesure_path() 时,一切正常:

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

【问题讨论】:

    标签: namespaces ruby-on-rails-3.2 form-for nested-resources


    【解决方案1】:

    无视!这不是错误。

    我解决了这个问题。 问题的根源在于控制器:

    我没有正确实例化@proj_paquet_mesures。 相反,它持有 'nil' 值。

    这导致 form_for 的行为就像我用 :

    调用它一样
    form_for (:projects, @proj_mesure) do |f|
    

    生成的 HTML 是:

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

    所以要纠正这个问题,我只需要修改我的控制器:

      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
    

    这是完美的工作:

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

    【讨论】:

      猜你喜欢
      • 2011-02-12
      • 1970-01-01
      • 1970-01-01
      • 2016-09-23
      • 2012-10-22
      • 2011-07-06
      • 1970-01-01
      • 2012-10-02
      • 2011-01-03
      相关资源
      最近更新 更多