通过控制器查询提取Activerecord连接表信息

时间:2018-11-19 22:42:15

标签: ruby-on-rails ruby join activerecord controller

我有一个查询,该查询生成了产品数据列表;我正在努力进行更深入的研究,并从联接表(ProductSelections)中提取属性。 RFIDTag和产品都具有许多“产品选择”模型(即,模式表同时包含rfid_tag_id和product_id)。由于我是从产品列表中进行工作的,因此我从这里派生查询:

#original query (works as needed):

@warehoused_products = Product.includes(:rfid_tags).joins(:rfid_tags).where("rfid_tags.location_type = 'Warehouse' AND rfid_tags.location_id = ?", params[:id]) 

#Attempt at getting product selection data:

@product_histories = @warehoused_products.joins("INNER JOIN product_selections ON :product_selections.product_id = products.id").includes(:product_selections)

这在我检查时会引发相当大的postgreSQL错误:

raise @product_histories.inspect:

PG::SyntaxError: ERROR: syntax error at or near ":" LINE 1: ...eted_at" IS NULL INNER JOIN product_selections ON :product_s...

关于调整查询:

raise @warehoused_products.includes(:product_selections).joins(:product_selections).where("product_selections.product_id = ?", params[:product_id]).first.inspect

我得到一个nil的结果-没有错误,而且可能更干净,但还不完全。

产品选择对象如下所示,供参考:

#<ProductSelection id: 269, user_id: 2, listing_id: 11, product_id: 35, created_at: "2016-07-14 15:38:11", updated_at: "2016-08-08 21:10:13", rfid_tag_id: 575, part_id: nil, use_time: 2173274, account_id: 1, deleted_at: nil>

如何解决查询,以便可以提取关联的表对象?

1 个答案:

答案 0 :(得分:0)

@warehoused_products = Product.includes(:rfid_tags).where("rfid_tags.location_type = ? AND rfid_tags.location_id = ?", 'Warehouse', params[:id]) 


@product_histories = @warehoused_products.includes("product_selections").where("product_selections.product_id = ?", params[:product_id]).first.inspect