新手问题 關於 joins (已解決)

xdxie · 2012年12月12日 · 最后由 xdxie 回复于 2012年12月12日 · 2409 次阅读

#model file

class Product < ActiveRecord::Base
    belongs_to:product_type     
end

#view

<%=debug(@products.product_type)%>

#controller case1

@products=Product.joins(:product_type).all

#controller case2

@products=Product.all

我想請問 case1 與 case2 差異在哪? 我在測試的時候即使沒有使用.joins(:product_type),在 view 裡一樣可以成功取得 product_type

問題已解決 使用 joins 產生的 sql log Product Load (0.1ms) SELECT "products".* FROM "products" INNER JOIN "product_types" ON "product_types"."id" = "products"."product_type_id" ProductType Load (0.2ms) SELECT "product_types".* FROM "product_types" WHERE "product_types"."id" = 2 ORDER BY ord asc LIMIT 1

沒有使用 joins 產生的 sql log Product Load (0.1ms) SELECT "products".* FROM "products" ProductType Load (0.1ms) SELECT "product_types".* FROM "product_types" WHERE "product_types"."id" = 2 ORDER BY ord asc LIMIT 1

1 楼 已删除

問題是如果 model 裡沒有 belongs_to 的話在 controller 使用 joins 會出現 錯誤:Association named 'product_type' was not found; perhaps you misspelled it

我错了,我没动手

默认的 joins 是 inner join, 只会查出 products 关联的 product_types 表中 product_id 存在的数据,直接用 all 就是查处 products 表中所有数据

去数据库中写几条 sql 语句就明白了

select count(*) from products p inner join product_types py on py.product_id = p.id;

select count(*) from products p left join product_types py on py.product_id = p.id;

select count(*) from products;

#4 楼 @diudiutang "py.product_id = p.id"應該是"py.id = p.product_type_id" 我只知道 joins 是 inner join 沒錯,跑三條 SQL 出來的 count 都是 1

觀察 sql log 後,問題已解決。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号