【发布时间】:2017-09-23 17:26:10
【问题描述】:
我目前正在尝试使用 ajax,这是我遇到的错误。
ActiveRecord::RecordNotFound at /books/index.找不到具有 'id'=index 的图书
我的意图是,当我单击“选择”并更改值而不重新加载时,我希望书籍的卡片自行排序。因此,我使用了js和ajax,但目前我仍在进行中。
图书索引.html.erb
<select id="priceSelect">
<option value="Best Results" selected="selected">Best Results</option>
<option value="Price Descending">Price Descending</option>
<option value="Price Ascending">Price Ascending</option>
</select>
.
.
.
<% @books.each do |book| %>
<div class="col-xs-12 selectable-card">
<%= link_to book_path(book.id) do %>
...
<% end %>
</div>
<% end %>
<script>
$('#priceSelect').change(function(){
$.ajax({
url: "books/index",
type: "GET",
data: {sort: $('#priceSelect :selected').val()},
success:function(result){
console.log(result);
},
})
});
</script>
这是我的 BooksController.rb
before_action :set_book, only: [:show, :edit, :update, :destroy]
def index
if params[:book][:title].present? && params[:users][:university].present?
@books = Book.where({title: params[:book][:title]})
.joins(:user).where(users: {university: params[:users][:university]})
elsif !params[:users][:university].present? && params[:book][:title].present?
@books = Book.where({title: params[:book][:title]})
elsif params[:users][:university].present? && !params[:book][:title].present?
@books = Book.joins(:user).where(users: {university: params[:users][:university]})
else
@books = Book.all
end
case params[:sort]
when "Price Descending"
@books.order(price_cents: "DESC")
when "Price Ascending"
@books.order(price_cents: "ASC")
else
@books.sort_by(&:created_at)
end
end
我真的不明白为什么会出现这个错误,因为我声明这个方法应该只适用于 [:show] 等......而不适用于 [:index]。该错误表明这是因为我的 BooksController 中的那一行。
private
def set_book
@book = Book.find(params[:id])
end
最后是我的 routes.rb
resources :books do
resources :users
end
【问题讨论】:
-
您在 URL 中向它传递了一个 ID 为“index”。不要,没必要。对根书籍路由的 GET 请求。
-
您想在 ajax 中点击图书索引操作吗?
标签: jquery ruby-on-rails ajax