编辑:
我希望我的索引根据价格下降和价格上涨来改变,就像亚马逊一样。
现在,我向网站发送一个ajax请求,其中select的新值请求数据。该站点从数据库中获取数据并对其进行排序。
我的javascript如何获取已排序的图书回复并在我的索引页面中重新绘制卡片?
BookController.rb
def index
if params.dig("book", "title").nil? && params.dig("users", "university").nil?
@books = Book.where({title: params.dig("book", "title")})
.joins(:user).where(users: {university: params.dig("users", "university")})
elsif !params.dig("book", "title").nil? && params.dig("users", "university").nil?
@books = Book.where({title: params.dig("book", "title")})
elsif params.dig("book", "title").nil? && !params.dig("users", "university").nil?
@books = Book.joins(:user).where(users: {university: params.dig("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
预订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>
最后我的routes.rb
resources :books do
resources :users
end
答案 0 :(得分:0)
执行以下操作非常简单。有更好的方法可以做到这一点但是,对于您可以通过最少的逻辑更改完成后续操作,请为您的选择提供一个ID,例如&#34;排序&#34;
@books = Book.order(price: sort_order.to_sym)
private
def sort_order
return "Asc" if params[:sort].nil?
return params[:sort] == "Price Descending" ? "Desc" : "Asc"
end
答案 1 :(得分:0)
您可以通过以下代码实现此目的
def index
@books = Book.all
case params[:sort]
when "Price Descending"
@books.order(price: "DESC")
when "Price Ascending"
@books.order(price: "ASC")
else
# add the best results query here
end
end
请修改您的脚本代码
$( document ).ready(function() {
$('#sort').change(function(){
var sort = $('#sort :selected').val();
$.ajax({
url: "books/index",
type: "GET",
data: {sort: $('#sort :selected').val()},
})
});
});
干杯!