Rails-按联接表数据排序 [英] Rails - Sort by join table data

查看:86
本文介绍了Rails-按联接表数据排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作中有一个RoR项目.这是我模型的适用部分.

I've got a RoR project in the works. Here are the applicable sections of my models.

首页

has_many :communities, :through => :availabilities
has_many :availabilities, :order => "price ASC"

社区

has_many :homes, :through => :availabilities
has_many :availabilities

可用性

belongs_to :home
belongs_to :community

数据库中的可用性"表具有附加数据列价格"

现在我可以打电话

@home.availabilities.each do |a|
  a.community.name
  a.price

,然后根据需要返回按价格排序的可用性数据.我的问题是这样:

and get back the availabilities data ordered by price as I want. My question is this:

是否可以通过avaliabilities.first.price(第一个=最低)自动订购房屋?也许跟default_scope :order有什么关系?

Is there a way to automatically order Homes by avaliabilities.first.price (first = lowest)? Maybe something with default_scope :order?

推荐答案

我建议避免使用default_scope,尤其是在另一张桌子上标价的情况下.每次使用该表时,都会进行联接和排序,在复杂的查询中可能会产生奇怪的结果,反而会使查询变慢.

I would suggest to avoid using default_scope, especially on something like price on another table. Every time you'll use that table, join and ordering will take place, possibly giving strange results in complex queries and anyway making your query slower.

它自己的范围没有什么问题,它更简单,甚至更清晰,您可以将其简单化为:

There's nothing wrong with a scope of its own, it's simpler and it's even clearer, you can make it as simple as:

scope :ordered, -> { includes(:availabilities).order('availabilities.price') }

PS:请记住在price上添加索引;另请参见此处的其他一些很好的答案,以便在 join/include 之间进行选择.

PS: Remember to add an index on price; Also see other great answers in here to decide between join/include.

这篇关于Rails-按联接表数据排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆