使用 Rails Helpers 按多个字段排序
我有这两个表:
room_types
+ id
+ n_adults
+ n_children
rooms
+ id
+ name
+ hotel_id
+ room_type_id
我想列出由 n_adults ASC 订购的所有房间。但是,如果两个房间具有相同的 n_adults 值,我想按 n_children ASC 对它们进行排序。
到目前为止我有这个:
<% Room.all(:conditions => ['rooms.hotel_id = ?', @hotel_id], :joins => :room_type, :order => "room_types.n_adults ASC").each do |room| %>
我怎样才能做到这一点?
谢谢你哟!!!
=)
示例:
room 1 Adults: 1 Children: 0
room 2 Adults: 1 Children: 1
room 3 Adults: 2 Children: 1
room 4 Adults: 3 Children: 0
room 5 Adults: 3 Children: 1
room 6 Adults: 3 Children: 2
I have this two tables:
room_types
+ id
+ n_adults
+ n_children
rooms
+ id
+ name
+ hotel_id
+ room_type_id
I want to list all my rooms ordered by n_adults ASC. However, if two rooms have the same n_adults value, I want to sort them by n_children ASC.
So far I have this:
<% Room.all(:conditions => ['rooms.hotel_id = ?', @hotel_id], :joins => :room_type, :order => "room_types.n_adults ASC").each do |room| %>
How can I accomplish that?
Thank youuu!!!
=)
Example:
room 1 Adults: 1 Children: 0
room 2 Adults: 1 Children: 1
room 3 Adults: 2 Children: 1
room 4 Adults: 3 Children: 0
room 5 Adults: 3 Children: 1
room 6 Adults: 3 Children: 2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这应该可以解决问题:
它会生成一个 SQL ORDER BY 子句:
如果您使用的是 Rails 3 或更高版本,您可能希望使用较新的查询 API,例如:
请参阅 http://guides.rubyonrails.org/active_record_querying.html
This should do the trick:
It generates a SQL ORDER BY clause of:
If you are using Rails 3 or above you might like to use the newer query API, e.g.:
See http://guides.rubyonrails.org/active_record_querying.html