【发布时间】:2014-01-09 16:42:56
【问题描述】:
我们谈论的是一个简约的嵌套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,而不是向我显示错误。
我错过了什么?
控制器:
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
【问题讨论】:
-
能否也显示相关的路由定义?
-
你能做
rake routes并验证是否存在该路线吗? -
评论是嵌套的,所以 cmets_path 应该是 screen_cmets 就像在 rake 路由中一样。但我不知道这里出了什么问题:(
-
有趣的答案,但我不明白在我的情况下这对我有什么帮助..
标签: ruby-on-rails validation controller ruby-on-rails-4 nomethoderror