0

我关注了这一集http://railscasts.com/episodes/136-jquery-ajax-revised 并创建了我的 cusotm 示例。我将创建表单放入索引中,并通过远程方法创建一本书

但我不知道如何在页面中放置错误消息。请举个例子,谢谢~

指数

<%= 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

创建.je.erb

<%  unless @book.save   %>

<% else %>

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

1 回答 1

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

然后,在 you 中create.js.erb,您将要检查您的书是否是persited?

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

假设我们要在<p>类中显示错误消息.errors

$('<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 %>
于 2013-09-02T00:25:28.107 回答