给定生成以下 SQL 的 2 个 ActiveRecord 关系:
- 关系
a = SELECT comments.* FROM comments INNER JOIN attachments ON attachments.comment_id = comments.id WHERE attachment.name ILIKE '%foo%
- 关系
b = SELECT attachments.* FROM attachments INNER JOIN users ON attachments.user_id = users.id WHERE users.other_conditions
这在 Rails/ActiveRecord 3中有效:
puts a.merge(b).to_sql # Rails 3
> "SELECT comments.* FROM comments INNER JOIN attachments ON attachments.comment_id = comments.id INNER JOIN users ON attachments.user_id = users.id WHERE attachment.name ILIKE '%foo% AND users.other_conditions"
我认为它有效,因为它merge
忽略了查询中任何不存在的关联。
但是 Rails 4更加迂腐,并且失败了:
puts a.merge(b).to_sql # Rails 4
> ActiveRecord::ConfigurationError: Association named 'user' was not found on Comment; perhaps you misspelled it?
所以问题是我如何才能在 Rails 不担心正确性的情况下真正合并这两个关系(我的规范对此负责)?