首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过控制器查询拉取Activerecord连接表信息

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

Stack Overflow用户
提问于 2018-11-20 06:42:15
回答 1查看 43关注 0票数 0

我有一个查询,它生成了一个产品数据列表;我正在更深入地挖掘,并从连接表(ProductSelections)中提取属性。RFIDTag和Products都有许多产品选择模型(即模式表包含一个rfid_tag_id和一个product_id)。由于我是从产品列表开始工作的,所以我的查询是从以下内容派生出来的:

代码语言:javascript
复制
#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错误:

代码语言:javascript
复制
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...

在调整查询时:

代码语言:javascript
复制
raise @warehoused_products.includes(:product_selections).joins(:product_selections).where("product_selections.product_id = ?", params[:product_id]).first.inspect

我得到了一个nil结果--没有错误,而且可能更干净,但并不完全是这样。

Product Selection对象如下所示,以供参考:

代码语言:javascript
复制
#<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>

如何解析查询,以便拉出关联的表对象?

EN

回答 1

Stack Overflow用户

发布于 2018-11-20 15:05:58

代码语言:javascript
复制
@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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53383703

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档