验证失败的奇数NoMethodError

时间:2013-08-22 14:50:24

标签: ruby-on-rails validation

当一个表单在Rails中验证失败时,我出现了一个奇怪的NoMethodError。我可以毫无问题地访问“新”方法,以便第一次填写表单。但随后表单提交给嵌套控制器,如果验证失败,它会再次尝试重定向到“new”(应该如此)但抛出undefined method articles_path

我认为它可能与嵌套有关,但我相信这里的设置对于加载嵌套的“新”路径是正确的吗?

我确定我错过了一些明显的东西......但为什么会这样呢?

控制器:

  def new
    @user = User.find(current_user)
    @article = Article.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @article }
    end
  end

  def create
    @article = current_user.articles.build(params[:article])

    respond_to do |format|
      if @article.save
        format.html { redirect_to root_path, :flash => { :notice => 
          "Article added!" } }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @article.errors, :status => 
          :unprocessable_entity }
      end
    end
  end

形式:

= form_for([@user, @article], :html => { :multipart => true }) do |f|
  - if @article.errors.any?
    #errorExplanation
      %h2
        = pluralize(@article.errors.count, "error")
        prohibited this post from being saved:
      %ul
        - @article.errors.full_messages.each do |msg|
          %li= msg

  .clearfix
    = f.label :title, "Article title *"
    .input
      = f.text_field :title

1 个答案:

答案 0 :(得分:3)

你是对的,错误是由嵌套资源引起的,特别是代码的这部分

= form_for([@user, @article], :html => ...

验证失败时,@user为nil会导致网址看起来像[nil, @article],如果@article没有保留,则会变成articles_path。因此,解决方案是在创建操作中设置@user