2016-04-15 43 views
-2

我想知道如何使用where cause with the ActiveRecord查找方法。使用.where與.find

這裏是我使用的代碼:這使我

Supplier.joins(:products).find(params[:id]).where('suppliers.permalink = ? AND variants.master = ?', params[:id], TRUE) 

undefined method `where' for #<Supplier:0x007fe49b4eb330> 
+2

什麼是預期的結果?比如,你想從數據庫中獲得什麼? params [:id]是真的永久鏈接? – lcguida

回答

1
Supplier.joins(:products).find(params[:id]).where('suppliers.permalink = ? AND variants.master = ?', params[:id], TRUE) 

你在做什麼這裏是ID爲找到的第一個記錄包含在params[:id]中,然後嘗試在該單個記錄上運行where聲明。 where僅在與模型本身運行時才起作用。

這裏令人困惑的部分是,您正在使用params[:id]這兩個主鍵(find搜索ID字段),但然後還將它與where子句中的permalink列進行比較。

爲了解釋這兩種方法的用法:

find將搜索從表中的結果(S),匹配你把它提供給id領域的說法。你可以傳入多個id,這個方法主要用於通過id來選擇你知道存在的行。最常見的是它與一個id一起使用並返回一個實例。

where用於查找表中與該子句匹配的所有結果並返回記錄集合。然後,您可以通過使用.first縮小搜索結果,或者選擇一個,例如:

Supplier.joins(:products).where('suppliers.permalink = ? AND variants.master = ?', params[:permalink], true).first 

(請注意,您正在使用joins(:products)但隨後查詢variants表這是不正確?)

+0

我通過以下參考變體: - @ supplier.variants.each do | item | = render:partial =>'product',:locals => {:item => item}' –

-1
Supplier.joins(:products).where('suppliers.permalink = ? AND variants.master = ?', params[:id], TRUE).find(params[:id]) 
+0

這真的不會返回我期待的sql,它是 'SELECT suppliers.id as supp_id,products.id作爲prod_id,products.name作爲prod_name,product_types.name作爲供應商的prod_type INNER JOIN variant_suppliers on variant_suppliers。 supplier_id = suppliers.id INNER JOIN上variants.id = variant_suppliers.variant_id變體 INNER JOIN產品上products.id = variants.product_id INNER JOIN上product_types.id = products.product_type_id product_types WHERE suppliers.id(1)中和variants.master = TRUE' –

+0

當find執行查詢時,它將返回結果集而不是查詢(它存在於我們通過where使用的Active Relation對象中)。如果你需要SQL,那麼你將需要使用的地方。我很好奇爲什麼兩個都需要。你可以使用'where'與你使用'find'的條件相同。 –