例如我有两个表,是一对一,配件和库存,fitting 和 stock。 我想搜索,库存位 0 的 fitting。 因为我 views 中是`@fitting = Fitting.all" 当搜索库存为 0 的 fitting,就会产生一个 params[:search] = true
if params[:search] = false
@fitting = Fitting.all
else
@fitting = Fitting.stock.where("数量 != 0") #不可用
end
请问在不可用
那列应该怎么表达比较好呢?
irb(main):013:0> Fitting.all[0].stock.amount
Fitting Load (3.1ms) SELECT `fittings`.* FROM `fittings` ORDER BY id desc
Stock Load (0.3ms) SELECT `stocks`.* FROM `stocks` WHERE `stocks`.`fitting_id` = 1753 ORDER BY id desc LIMIT 1
=> #<BigDecimal:cdc1f84,'0.1E1',9(18)>
使用:
irb(main):017:0> Fitting.includes(:stock).where("stock.amount != ?", 0)
SQL (1.4ms) SELECT `fittings`.`id` AS t0_r0, `fittings`.`name` AS t0_r1, `fittings`.`price` AS t0_r2, `fittings`.`created_at` AS t0_r3, `fittings`.`updated_at` AS t0_r4, `fittings`.`selling_price` AS t0_r5, `fittings`.`barcode` AS t0_r6, `fittings`.`unit` AS t0_r7, `fittings`.`genre` AS t0_r8, `fittings`.`store_house_id` AS t0_r9, `fittings`.`shipping_space_id` AS t0_r10, `stocks`.`id` AS t1_r0, `stocks`.`amount` AS t1_r1, `stocks`.`fitting_id` AS t1_r2, `stocks`.`created_at` AS t1_r3, `stocks`.`updated_at` AS t1_r4, `stocks`.`alarm` AS t1_r5 FROM `fittings` LEFT OUTER JOIN `stocks` ON `stocks`.`fitting_id` = `fittings`.`id` WHERE (stock.amount != 0) ORDER BY id desc
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'stock.amount' in 'where clause
irb(main):018:0> Fitting.includes(:stock).where("amount != ?", 0)
Fitting Load (0.8ms) SELECT `fittings`.* FROM `fittings` WHERE (amount != 0) ORDER BY id desc
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'amount' in 'where clause': SELECT `fittings`.* FROM `fittings` WHERE (amount != 0) ORDER BY id desc
上面都是不成功的。唯独下面的成功了,使用 joins 反而可以了。。
irb(main):019:0> Fitting.joins(:stock).where("amount != ?", 0)
不清除是什么个状况。