简体   繁体   中英

Active record queries - chaining

I am trying to convert the following query into something better, using parameters for example.

I am new to active record and rails so still learning. But the null part is throwing me off. Since this needs to work on both mysql and sql server.

contacts = contacts.where("key_contact = true and (c_contact is null or c_contact = false)")

I should not that key_contact and c_contact are in a different table called main_contacts. The contacts table has_many main_contacts

Anyone help?

I'd say:

contacts = contacts.where(key_contact: true).where(c_contact: [nil, false])

In console check the resulting query appending .explain

Should be equivalent to:

contacts = contacts.where(key_contact: true).where.not(c_contact: true)

Anyway, you should keep consistency in your database. So for booleans, have a default value to prevent null .


Per your comment:

contacts = contacts.joins(:main_contacts).where(main_contacts: { key_contact: true }).where.not(main_contacts: { c_contact: true })

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