破解验证时的NoMethodError

时间:2014-01-09 16:42:57

标签: ruby-on-rails validation controller ruby-on-rails-4 nomethoderror

我们正在讨论一个简约的嵌套Comment's Controller

验证为validates :body, :presence => true

现在,编辑评论有效,如果我创建新评论并打破验证,则会正常显示。

我的问题是当我编辑评论并删除他的遗体时,我应该得到关于身体的错误,而不是我得到NoMethodError in Comments#update

问题扩展=> 通常,当我成功修改评论(http://localhost:3000/s/38/comments/11/edit)时,它会将我重定向到@screen http://localhost:3000/s/38。但如果我清空身体并尝试提交,它会将我重定向到http://localhost:3000/s/38/comments/11,而不是向我显示错误。

enter image description here

我缺少什么?

控制器:

def update
    respond_to do |format|
      if @comment.update(comment_params)
        format.html { redirect_to @comment.screen, notice: 'Comment was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

我的编辑表格:

<%= form_for([@screen, @comment]) do |f| %>

  <div class="panel panel-default">
    <div class="panel-heading">
      <h1>Edit your Comment</h1>
      <% if @comment.errors.any? %>
        <div id="error_explanation">
          <h3><%= pluralize(@comment.errors.count, "error") %> prohibited this comment from being saved:</h3>

          <ul>
            <% @comment.errors.full_messages.each do |msg| %>
              <li><%= msg %></li>
            <% end %>
          </ul>
        </div>
      <% end %>
    </div>

    <div class="panel-body">
      <div class="form-group">
        <%= f.label :body, "Comment" %>
        <%= f.text_area :body, autofocus: true, class: "form-control" %>
      </div>
    </div>

    <div class="panel-footer">
      <%= f.submit "Edit Comment", class: "btn btn-primary" %>
      <%= link_to "Back", @screen, class: "btn btn-primary" %>
    </div>
  </div>

<% end %>

我的路线:

resources :screens, :path => 's' do
    resources :comments
    member do
      get :like
      get :unlike
    end
  end
    screen_comments GET    /s/:screen_id/comments(.:format)          comments#index
                     POST   /s/:screen_id/comments(.:format)          comments#create
  new_screen_comment GET    /s/:screen_id/comments/new(.:format)      comments#new
 edit_screen_comment GET    /s/:screen_id/comments/:id/edit(.:format) comments#edit
      screen_comment GET    /s/:screen_id/comments/:id(.:format)      comments#show
                     PATCH  /s/:screen_id/comments/:id(.:format)      comments#update
                     PUT    /s/:screen_id/comments/:id(.:format)      comments#update
                     DELETE /s/:screen_id/comments/:id(.:format)      comments#destroy

1 个答案:

答案 0 :(得分:0)

使用像这样的多态路由的表单将始终使用复数路径来创建新记录。我需要以我的形式明确:

form_for([@user, @profile], :url => user_profile_path(@user))