處理錯誤 - 未定義的方法,其中 Array0x000000071923f8
有時我們想對返回的記錄集合使用 where
查詢,這不是 ActiveRecord::Relation
.Hence 我們得到上述錯誤,因為 Where
子句知道 ActiveRecord
而不是 Array
。
使用 Joins
有一個精確的解決方案。
示例 : -
假設我需要找到所有使用者配置檔案(UserProfile),這些配置檔案是活動的,而不是 id = 10 的使用者(User)。
UserProfiles.includes(:user=>:profile_pictures]).where(:active=>true).map(&:user).where.not(:id=>10)
所以上面的查詢將在 map
之後失敗,因為 map
將返回 array
,這將不適用於 where
子句。
但是使用連線,會使它工作
UserProfiles.includes(:user=>:profile_pictures]).where(:active=>true).joins(:user).where.not(:id=>10)
由於 joins
將輸出類似 map
的類似記錄,但它們將是 ActiveRecord
而不是 Array
。