简体   繁体   English

在Rails ActiveRecord中按存在多个has_one关联进行排序

[英]Order by existence of multiple has_one associations in Rails ActiveRecord

Hi I want to order my Rails AR query by existence of multiple has_one associations but with an OR 嗨,我想通过存在多个has_one关联但使用OR来对Rails AR查询进行排序

The idea is to have something like below... but wanna use it in order . 这个想法是要像下面这样...但是要按order使用它。

IF `guest_listings`.`user_id` IS NOT NULL OR `minor_listings`.`user_id` IS NOT NULL

I've been seeing something like this, but maybe for has_many associations? 我一直在看到这样的东西,但也许是针对has_many关联?

User.select('guest_listings.*, count(users.id) as counter').order('counter DESC')

^ also not sure how to add an OR minor_listings*. ^也不确定如何添加OR( minor_listings*. here 这里

I'm new to Rails. 我是Rails的新手。 Thank you. 谢谢。

You can just use that statement in your order() (without the if ). 您可以只在order()使用该语句(不使用if )。 But you will need to joins() those other two tables. 但是您将需要joins()其他两个表。

UPDATE UPDATE

Be careful when using select and fields from other tables. 使用其他表中的select和字段时要小心。 The result might be unexpected. 结果可能是意外的。

Your statement could look something like this: 您的声明可能如下所示:

User.select('`users`.*,  `guest_listings`.`user_id` IS NOT NULL OR `minor_listings`.`user_id` IS NOT NULL as o').joins(:guest_listings, :minor_listings).order('o desc')

( desc if entries with true should be ordered first) desc如果与项目true要责令先)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM