Reputation: 2289
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?
Upvotes: 0
Views: 48
Reputation: 115521
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 })
Upvotes: 1