我是 Rails 新手,我正在尝试为学校做一个简单的项目。
我已经生成了一个脚手架,如下所示。
rails generate scaffold Book title:string content:text code:string
我想做的是,当我单击链接时,在同一页面(localhost:3000/books)的 div 中显示书籍 id 的列表。我试图关注this程序,但它似乎不起作用,当我单击/books 页面末尾的链接时,页面上没有明显呈现任何内容
这是我的 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 %>
和 books/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
最佳答案
Rails 5.1 不依赖于 jQuery。这段代码:
$('#content').html("<%= j (render 'books') %>");
是 jQuery 代码。如果您添加 jquery-rails
gem 并遵循文档,您的代码应该可以工作。
关于javascript - 使用ajax请求在同一页面中显示部分内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43941608/