鑑於2個ActiveRecord的關係,不同的表生成SQL語句:如何合併(鏈接)2間的關係在軌道4個
- 關係
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
這個工作在軌道/ ActiveRecord :
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的更加顯得很迂腐,失敗:
puts a.merge(b).to_sql # Rails 4
> ActiveRecord::ConfigurationError: Association named 'user' was not found on Comment; perhaps you misspelled it?
所以,問題是我怎麼可以從字面上合併2間的關係,而不Rails的是擔心正確性(我的規格承擔的責任)?
檢查由Rails內部使用的Arel gem - https://github.com/rails/arel以及這裏的一些示例/規格https://github.com/rails/arel/tree/master/test你可能會得到一些更多的見解。 –
@OtoBrglez在那裏找不到任何指針。你有什麼? –