【发布时间】:2017-10-12 00:03:29
【问题描述】:
我是 Rails 新手,我正在尝试为学校做一个简单的项目。
我已经生成了一个脚手架,如下所示。
rails generate scaffold Book title:string content:text code:string
我想要做的是,当我点击一个链接时,在同一页面 (localhost:3000/books) 的一个 div 中显示书籍 ID 的列表。我尝试遵循this 程序,但它似乎不起作用,当我单击 /books 页面末尾的链接时,页面上没有明显呈现任何内容
这是我的书/index.html.erb
<p id="notice"><%= notice %></p>
<h1>Books</h1>
<table>
<thead>
<tr>
<th>Title</th>
<th>Content</th>
<th>Code</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @books.each do |book| %>
<tr>
<td><%= book.title %></td>
<td><%= book.content %></td>
<td><%= book.code %></td>
<td><%= link_to 'Show', book %></td>
<td><%= link_to 'Edit', edit_book_path(book) %></td>
<td><%= link_to 'Destroy', book, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Book', new_book_path %>
<br>
<%= link_to 'All books', books_path, remote: true %>
<br>
<br>
<div id="content" >
</div>
我的 books_controller 的索引方法
def index
@books = Book.all
respond_to do |format|
format.html
format.js
end
end
_books 部分
<% @books.each do |book| %>
<div class="book">
<%= book.id %>
</div>
<% end %>
还有书籍/index.js.erb
$("#content").html("<%= j (render 'books') %>");
当我点击应该呈现部分的链接时,我在终端中得到了这个,页面上没有显示任何内容。
Started GET "/books" for 127.0.0.1 at 2017-05-12 17:35:02 +0200
Processing by BooksController#index as JS
Rendering books/index.js.erb
Book Load (0.3ms) SELECT "books".* FROM "books"
Rendered books/_books.html.erb (2.4ms) [cache miss]
Rendered books/index.js.erb (3.9ms)
Completed 200 OK in 8ms (Views: 6.0ms | ActiveRecord: 0.3ms)
我想我错过了什么,但我真的不知道为什么。有任何想法吗?谢谢
PS:Rails 版本:5.1.0 和 ruby 2.4.0
【问题讨论】:
-
打开浏览器控制台并单击链接。您应该会看到一个请求被触发。该请求的响应是什么?
-
我没有看到带有
id=content的 div/container,所以,我猜事情没有被替换,因为没有具有该 ID 的容器。 -
@fanta 它在最底层
-
@SebastiánPalma 在这里你可以找到我的代码github.com/engid87/books
标签: javascript jquery ruby-on-rails ruby ajax