하이 뷰 검증 :레일 4는 오류 메시지 I 자원 중첩 된
resources :posts do
resources :msgs
end
일부 검증 :
class Msg < ActiveRecord::Base
belongs_to :post
validates :body ,presence:true
end
컨트롤러 :
# msgs_controller.erb
def create
@post = Post.find(params[:post_id])
@[email protected](msg_params)
@msg.user=current_user
@msg.email=current_user.email
@msg.autor=current_user.name
if @msg.save
flash[:notice] = t '.create'
end
respond_with(@post,@msg)
end
및 도면 : EDIIT : /views/posts/show.html.rb # /views/show.html.erb
<h2>Add a comment:</h2>
<%= form_for([@post, @post.msgs.build]) do |f| %>
<% if @msg.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@msg.errors.count, "error") %> prohibited this msg from being saved:</h2>
<ul>
<% @msg.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :body %><br />
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
본문 필드가 비어있을 때 앱에서 오류 메시지를 표시하지 않지만 서버가 COMMIT 대신 ROLLBACK을 표시하기 때문에 유효합니다. 문제는보기에 오류 메시지를 표시하는 것입니다. 도와 주실 수 있습니까?
모든'@의 msg.errors'에 있나요을? '@ msg'의 데이터는 저장하려고 할 때 실제로 어떻게 생겼을까요? 당신은 ROLLBACK을 수행하고 있다고 언급하지만, 유효성 검사가 실제로 실패하면 INSERT를 전혀 시도하지 않을 것입니다. http://edgeguides.rubyonrails.org/active_record_validations.html#presence - 섹션 1.2, 두 번째 단락을 참조하십시오. 이는 유효성 검사가 실제로 실패하지 않고 다른 것이 저장에 잘못 될 수 있음을 나타냅니다 (ROLLBACK을 유발 함). –
'Posts' 모델에'accepts_nested_attributes_for : msg'가 있습니까? 그렇다면 오류가'@ post.errors'에 대신 나타나는지 궁금합니다. 어쩌면 그것을 시도해보십시오. – lurker
나는 msg 모델에서 유효성 검사를 제거하려고 시도했으며 blanck 주석은 db에서 커밋됩니다. 유효성 검사가 활성화되면 blanck 주석은 커밋되지 않지만 롤백됩니다. 나는 이것을 서버의 로그와 데이터베이스 쿼리에서 보았다. – user1066183