我正在尝试将以下查询转换为更好的内容,例如使用参数。
我是活跃记录和铁杆的新手,所以还在学习。但零部分让我失望。因为这需要在mysql和sql server上工作。
contacts = contacts.where("key_contact = true and (c_contact is null or c_contact = false)")
我不应该将key_contact和c_contact放在名为main_contacts的不同表中。
联系人表has_many
main_contacts
有人帮忙吗?
答案 0 :(得分:1)
我说:
contacts = contacts.where(key_contact: true).where(c_contact: [nil, false])
在控制台中,检查附加.explain
应该相当于:
contacts = contacts.where(key_contact: true).where.not(c_contact: true)
无论如何,您应该保持数据库的一致性。因此对于布尔值,有一个默认值来阻止null
。
根据你的评论:
contacts = contacts.joins(:main_contacts).where(main_contacts: { key_contact: true }).where.not(main_contacts: { c_contact: true })