我目前正在嘗試使用ajax,而這是我得到的錯誤。Ajax NoMethodError在/ books未定義方法`[]'爲零:NilClass
NoMethodError at /books undefined method `[]' for nil:NilClass
我的意思是,我想要的圖書卡由自己來進行排序,當我點擊選擇和改變數值無需重新加載。因此,我使用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",
type: "GET",
data: {sort: $('#priceSelect :selected').val()},
success:function(result){
console.log(result);
},
})
});
</script>
這是我的BooksController.rb
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
該錯誤指示它不能加載拳頭線在我的控制器的我的索引方法。
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]})
該指數本身工作正常。它可以顯示所有我想要的內容,但只有當我將選擇選項更改爲其他值時,頁面纔會保持不變,並在控制檯中顯示該錯誤。
而且最後我的routes.rb
resources :books do
resources :users
end
哪一行會引發此錯誤? –
如果params [:book] [:title] .present那麼我用一個> def index 標記的那個? && params [:users] [:university] .present? @books = Book.where({title:params [:book] [:title]}) .joins(:user).where(users:{university:params [:users] [:university]}) –
Did您嘗試使用'url:"/books "'? –