2013-10-03 4 views
2

하이 뷰 검증 :레일 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을 표시하기 때문에 유효합니다. 문제는보기에 오류 메시지를 표시하는 것입니다. 도와 주실 수 있습니까?

+0

모든'@의 msg.errors'에 있나요을? '@ msg'의 데이터는 저장하려고 할 때 실제로 어떻게 생겼을까요? 당신은 ROLLBACK을 수행하고 있다고 언급하지만, 유효성 검사가 실제로 실패하면 INSERT를 전혀 시도하지 않을 것입니다. http://edgeguides.rubyonrails.org/active_record_validations.html#presence - 섹션 1.2, 두 번째 단락을 참조하십시오. 이는 유효성 검사가 실제로 실패하지 않고 다른 것이 저장에 잘못 될 수 있음을 나타냅니다 (ROLLBACK을 유발 함). –

+0

'Posts' 모델에'accepts_nested_attributes_for : msg'가 있습니까? 그렇다면 오류가'@ post.errors'에 대신 나타나는지 궁금합니다. 어쩌면 그것을 시도해보십시오. – lurker

+0

나는 msg 모델에서 유효성 검사를 제거하려고 시도했으며 blanck 주석은 db에서 커밋됩니다. 유효성 검사가 활성화되면 blanck 주석은 커밋되지 않지만 롤백됩니다. 나는 이것을 서버의 로그와 데이터베이스 쿼리에서 보았다. – user1066183

답변

0

양식은 new이어야하며 show보기가 아니어야합니다. 그런 다음 저장하지 않으면 페이지를 렌더링하여 오류를 표시 할 수 있습니다.

.... 
if @msg.save 
    flash[:notice] = t '.create' 
else 
    render 'new' 
end 
.... 
+0

네,이 글을 참고하십시오. http://archives.ryandaigle.com/articles/2009/8/10/what-s-new-in-edge-rails-default-restful-rending respond_with 메소드는 폼이 새로운 경우 응답합니다. 오류가 있습니다. 그래서 내가 메시지에 대한 새로운보기를 만들었습니다. 그리고 여기에 양식이 리디렉션됩니다 (오류가있는 경우). 그렇지 않으면 양식이 게시물 자원의 표시로 리디렉션됩니다. – user1066183

+0

질문에 'show'보기에 양식이 나타나고'new'에는 표시되지 않습니다. 이 기사를 보면'create'에'if'와'else' 조건이 있다는 것을 알 수 있습니다. 'else' (저장되지 않은 경우)는 폼을 RENDER해야하며'@ msg.errors.any? '는'true'이고 오류가 표시됩니다. 저장하지 않을 때 REDIRECT를 사용하면'@ msg.errors'가 생기지 않을 것입니다. ... – gabrielhilal

+0

고마워요. 이제는 행동을 완전히 이해했습니다. 내 문제는 오류와 함께 리디렉션해야합니다 : 새로운 있지만 공연 .. – user1066183

1

체크 아웃 플래시 메시지 레일 4 방식으로 수행하는 방법에 대한이 문서 : 문서에서 http://blog.remarkablelabs.com/2012/12/register-your-own-flash-types-rails-4-countdown-to-2013

:

# app/controllers/application_controller.rb 
class ApplicationController 
    ... 
    add_flash_types :error, :another_custom_type 
end 

# app/controllers/users_controller.rb 
class UsersController < ApplicationController 
    def create 
    ... 
    redirect_to home_path, 
     error: "An error message for the user" 
    end 
end 

# app/views/home/index 
<%= error %>