[英]How to use sort_by or order_by on view and controller with will_paginate?
In my rails application I am limiting the amount of rooms displayed on a page through pagination, I want to allow the user to order/sort the results to different columns of the room model. 在我的rails应用程序中,我通过分页来限制页面上显示的房间数量,我希望允许用户对结果进行排序/排序到房间模型的不同列。 I think I will need a drop down menu to do this, and then pass this data over to my rooms_controller maybe through an instance variable. 我想我需要一个下拉菜单来执行此操作,然后通过实例变量将此数据传递给我的rooms_controller。
How can I sort the rooms with the select tag according to a column and what do I need to do in the corresponding controller to make this work? 如何根据列对具有select标签的房间进行排序,以及在相应的控制器中需要做什么才能使其工作?
At the moment I am using this for a drop down menu: 目前我正在使用它来下拉菜单:
index.html.erb index.html.erb
...
...
<%= will_paginate @rooms %>
<div id="order-by">
<select>
<option value="asc">Distance</option>
<option value="asc">Name</option>
<option value="asc">Price (low to high)</option>
<option value="des">Price (high to low)</option>
<option value="asc">Reviews</option>
</select>
</div>
rooms_controller.rb rooms_controller.rb
...
...
def index
@rooms = Room.paginate :page => params[:page], :per_page => 12
end
...
My room model has listing_name:string, address: string, nightly_price:integer and has_many reviews. 我的房间模型有listing_name:string,address:string,nightly_price:integer和has_many reviews。 My review model belongs_to room. 我的评论模型属于房间。 I am using geocoder gem for the location of an room. 我使用geocoder gem作为房间的位置。
I have searched allot and tried multiple things to make this work and I can not figure this one out. 我搜索了分配并尝试了多种方法来完成这项工作,我无法想出这一点。 For any hints on how to solve this I would be really happy! 有关如何解决这个问题的任何提示,我会非常高兴! If you need further information just let me know. 如果您需要更多信息,请告诉我。
Something like: 就像是:
index.html.erb index.html.erb
<%= will_paginate @rooms %>
<div id="order-by">
<form>
<select name="sort">
<option value="distance">Distance</option>
<option value="name">Name</option>
<option value="price">Price (low to high)</option>
<option value="price desc">Price (high to low)</option>
<option value="review">Reviews</option>
</select>
<input type="submit" value="Sort"/>
</form>
</div>
rooms_controller.rb rooms_controller.rb
def index
@rooms = Room.order(params[:sort]).paginate(page: params[:page], per_page: 12)
end
Also need to ensure that params[:sort]
is included into only available values, eg: 还需要确保params[:sort]
仅包含在可用值中,例如:
sort = params[:sort]
sort = nil unless sort.in?(['distance', 'name', 'price', 'price desc', 'review'])
@rooms = Room.order(sort).paginate(page: params[:page], per_page: 12)
Consider to use separate scope for sorting or some gem. 考虑使用单独的范围进行排序或使用某些gem。 eg ransack 例如hansack
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.