查询条件使HABTM关联无法正常工作

时间:2018-01-18 02:38:07

标签: ruby-on-rails join activerecord has-and-belongs-to-many

我想在HABTM协会中加入两个模型,设备和用户进行查询:

@device = Device.left_outer_joins(:users).where(users: {id: nil || 4})

我正在尝试在联接表中获取nil的任何用户或ID为4的用户。问题是此查询忽略nil条件并生成此:

SELECT `devices`.* FROM `devices` LEFT OUTER JOIN `devices_users` ON `devices_users`.`device_id` = `devices`.`id` LEFT OUTER JOIN `users` ON `users`.`id` = `devices_users`.`user_id` WHERE `devices`.`serial` = '1111-1111-10' AND `users`.`id` = 4

如何才能使此条件生效?

1 个答案:

答案 0 :(得分:1)

nil || 4评估为4,这就是查询忽略nil的原因。

如果稍微更改您的查询,它将起作用。试试这个:

@device = Device.left_outer_joins(:users).where(users: {id: [nil, 4]})

ActiveRecord将采用[nil, 4]数组并将其翻译为您正在寻找的查询。例如,您的查询的SQL将是这样的:

SELECT `devices`.* FROM `devices` LEFT OUTER JOIN `devices_users` ON `devices_users`.`device_id` = `devices`.`id` LEFT OUTER JOIN `users` ON `users`.`id` = `devices_users`.`user_id` WHERE `devices`.`serial` = '1111-1111-10' AND `users`.`id` = 4 OR `users`.`id` IS NULL

此外,这是ActiveRecord的一个非常巧妙的部分。你甚至可以给它一个包含更多id的数组,比如这个[nil, 4, 5],它会给你一样的SQL:

SELECT `devices`.* FROM `devices` LEFT OUTER JOIN `devices_users` ON `devices_users`.`device_id` = `devices`.`id` LEFT OUTER JOIN `users` ON `users`.`id` = `devices_users`.`user_id` WHERE `devices`.`serial` = '1111-1111-10' AND `users`.`id` IN (4, 5) OR `users`.`id` IS NULL