在渲染产品详细信息时出现Error,RuntimeError:找不到推断出价格的主变量

时间:2013-12-16 13:18:16

标签: ruby-on-rails-3 spree

尝试使用spree_variants,spree_taxons,spree_prices表通过使用以下查询来呈现产品详细信息:

result = Spree::Product
.select('spree_products.name as product_name, spree_prices.amount as cost_price, spree_variants.sku as variant_type')
.joins("LEFT JOIN spree_products_taxons ON spree_products.id = spree_products_taxons.product_id")
.joins("LEFT JOIN spree_taxons ON spree_products_taxons.taxon_id = spree_taxons.id")
.joins("LEFT JOIN spree_variants ON spree_products.id = spree_variants.product_id")
.joins("LEFT JOIN spree_prices ON spree_variants.id  = spree_prices.variant_id")
.where('spree_taxons.name = ? AND spree_taxons.taxonomy_id = ?', 'Bags', 1)

现在尝试通过以下循环呈现结果收集的结果:

 result.each do |item|
      puts item.product_name
      puts item.cost_price
      puts item.variant_type
  end       

此处在控制台中获取以下错误消息: 错误:

Spree::Variant Load (0.7ms)  SELECT `spree_variants`.* FROM `spree_variants` WHERE `spree_variants`.`product_id` = NULL AND `spree_variants`.`is_master` = 1 ORDER BY `spree_variants`.position ASC LIMIT 1
   (0.2ms)  BEGIN
   (0.4ms)  ROLLBACK
RuntimeError: No master variant found to infer price

1 个答案:

答案 0 :(得分:2)

使用内置的ActiveRecord功能来管理连接可能会更好:

result = Spree::Product.joins(:taxons => :taxonomy)
  .includes(:master)
  .where('spree_taxons.name' => 'Bags')
  .where('spree_taxonomies.name' => 'Categories')

我现在可以做到:

result.map { |product| [product.name, product.cost_price, product.sku] }