Wenqing Kevin Ma Wenqing Kevin Ma - 23 days ago 8
jQuery Question

Couldn't find Book with 'id'=index Rails Ajax JQuery

I am currently trying to work with ajax and I this is the error I am getting.


ActiveRecord::RecordNotFound at /books/index. Couldn't find Book with 'id'=index


My Intention is that I want the cards of the Books to sort by themselves when I click on the Select and change the value without reloading. Therefore, I use js and ajax but currently I am still in the process.

Book 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>


This is my 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


I really don't get why this error is appearing since I declared that this method should only work on [:show], etc... and not on [:index]. The error says that it's because of that that line here inside of my BooksController.

private

def set_book
@book = Book.find(params[:id])
end


And lastly my routes.rb

resources :books do
resources :users
end

Answer Source

*Replace

books/index

with just

/books

Because by default /books will hit index action only.If u pass anything after /books it will consider that as an id as mentioned in url.*

<script>
  $('#priceSelect').change(function(){
    $.ajax({
      url: "/books",
      type: "GET",
      data: {sort: $('#priceSelect :selected').val()},
      success:function(result){
        console.log(result);
      },
    })
  });
</script>