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

查看:23
本文介绍了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

数据库中的availabilities"表多了一个数据列price"

现在我可以打电话了

@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上加一个索引;还可以在此处查看其他很棒的答案,以决定 加入/包含.

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

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

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