我目前正在嘗試使用ajax,而且這是我得到的錯誤。找不到書'id'= index Rails Ajax JQuery
ActiveRecord :: RecordNotFound at/books/index。找不到書'id'=索引
我的意圖是,當我點擊選擇並更改該值而不重新加載時,我希望書籍的卡片能夠自行排序。因此,我使用js和ajax,但目前我仍處於這個過程中。
書Index.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
我真的不知道爲什麼,因爲我宣佈這個錯誤的出現,這種方法只工作on [:show]等等,而不是[:index]。該錯誤說,這是因爲在我的BooksController裏面的那一行。
private
def set_book
@book = Book.find(params[:id])
end
而且最後我的routes.rb
resources :books do
resources :users
end
你傳遞一個URL中'索引'的ID。不要,這不是必要的。根據您想要的路徑獲取根路線的GET請求。 –
你想在ajax中點擊書籍索引動作? – krishnar