简体   繁体   中英

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

The idea is to have something like below... but wanna use it in 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?

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

^ also not sure how to add an OR minor_listings*. here

I'm new to Rails. Thank you.

You can just use that statement in your order() (without the if ). But you will need to joins() those other two tables.

UPDATE

Be careful when using select and fields from other tables. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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