2013-09-02 2 views
0

에피소드 http://railscasts.com/episodes/136-jquery-ajax-revised 에 이어 내 cusotm 예제를 만들었습니다. 색인에 작성 양식을 작성하고 원격 메소드로 책을 만듭니다.레일즈에서 ujs를 사용하는 원격 메소드로 양식의 메시지 표시

그러나 페이지에 오류 메시지를 삽입하는 방법을 모릅니다. 좀 예를 들어주세요, 감사합니다 ~

인덱스

<%= render 'form' %> 

<p> 

<table id='books_tbl' class="table"> 
    <th>id</th> 
    <th>title</th> 
    <th>ISBN</th> 
    <th>sn</th> 
    <th>price</th> 
    <th>Functions</th> 
    <div class="books" id="books">  
     <%= render @existed_books %> 
    </div> 
</table> 

컨트롤러는

# POST /books 
# POST /books.json 
def create 
    @book = Book.new(params[:book]) 

    respond_to do |format| 

     if @book.save 
      format.html { redirect_to @book, notice: 'Book was successfully created.' } 
      format.json { render json: @book, status: :created, location: @book } 
      format.js 
     else 
      format.html { render action: "new" } 
      format.json { render json: @book.errors, status: :unprocessable_entity } 
      format.js  
     end 

create.je.erb

<% unless @book.save %> 

<% else %> 

    $('#books_tbl tr:last').after('<%= j render(@book) %>'); 
<% end %> 

답변

1

먼저 books_controller 그래서 그 변경 책이 있는지 항상 create.js.erb을 렌더링합니다. 지속 되었건 아니건간에.

def create 
    @book = Book.new(params[:book]) 

    respond_to do |format| 
    if @book.save 
     format.html { redirect_to @book, notice: 'Book was successfully created.' } 
     format.json { render json: @book, status: :created, location: @book } 
    else 
     format.html { render action: "new" } 
     format.json { render json: @book.errors, status: :unprocessable_entity } 
    end 
    format.js 
    end 
end 

그런 다음 create.js.erb에, 당신은 당신의 책이 있는지 여부를 확인하는 것이 좋습니다 persited? 여부 :

<% if @book.persisted? %> 
    # ... 
<% else %> 
    # display the error message 
<% end %> 

의 우리가 .errors 클래스와 <p>에서 오류 메시지를 표시하려고한다고 가정 해 봅시다 :

$('<p>').text('<%= @book.errors.full_messages.to_sentence.capitalize %>') 
    .prepend('form'); 

당신이 렌더링 할 때마다 오류 단락을 제거해야합니다. create.js.erb 그래서 전 오류가 곁에되지 않습니다 :

$('p.errors').remove(); 

모두 모두, 그것은 제공 : 당신의 도움에 대한

$('p.errors').remove(); 

<% if @book.persisted? %> 
    # ... 
<% else %> 
    $('<p>').text('<%= @book.errors.full_messages.to_sentence.capitalize %>') 
    .prepend('form') 
<% end %> 
+0

감사합니다 ~ 작동 – newBike