【问题标题】:Pull Activerecord join table information through controller query通过控制器查询拉取Activerecord连接表信息
【发布时间】:2019-04-22 08:21:33
【问题描述】:

我有一个生成产品数据列表的查询;我正在更深入地挖掘并从连接表(ProductSelections)中提取一个属性。 RFIDTag 和 Products 都有许多 Product Selections 模型(即模式表同时包含 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 结果 - 没有错误,而且可能更干净,但还不够。

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

#<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>

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

【问题讨论】:

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


    【解决方案1】:
    @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
    

    【讨论】:

    • 这是我尝试的第二件事 - 我从这里得到了nil(这个版本使它回到一个实例变量,但仍然一样)
    猜你喜欢
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 2022-11-11
    相关资源
    最近更新 更多