如何从自定义SQL查询中提取值 [英] How to extract values from a custom SQL query
本文介绍了如何从自定义SQL查询中提取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下自定义查询,我试图从中提取值,以便它们对我的应用有意义
I have the following custom query whereby I am trying to extract the values so they are meaningful for my app
@sizes = Product
.joins(:product_properties)
.joins('INNER JOIN variant_properties on product_properties.property_id = variant_properties.property_id')
.joins('INNER JOIN properties ON properties.id = product_properties.property_id AND properties.id = variant_properties.property_id AND properties.display_name = \'Size\'')
.joins('INNER JOIN variants on variants.product_id = products.id AND variants.id = variant_properties.variant_id')
.pluck('products.id as prod_id', 'LEFT(variant_properties.description,1) as short_desc', 'variants.price as price')
下面是我视图中的代码
- @sizes.each do |size|
- size.each do |var|
= var.price
= link_to var.short_desc, product, class: 'hollow button tiny'
%small= number_to_currency(var.price)
问题是我收到错误消息,指出没有固定的数字或没有定义的方法
Problem is I am getting an error either stating no fixed num or no defined methods
推荐答案
知道了,pluck
将返回一个数组数组,因此您不能像调用方法那样调用其元素.应该是size [0],size [1]....
Got it, pluck
will return an array of arrays so you cannot call its elements like calling methods. It should be size[0], size[1]... instead.
为便于使用,我建议您为此构建一个哈希值:
For the ease of use I suggest you build a hash for this:
@product_sizes = @sizes.each_with_object({}) do |size, result|
result[size[0]] = {
'short_desc' => size[1],
'price' => size[2]
}
end
然后在您的视图中使用它:
Then use it in your view:
- @products.each_with_index do |product, i|
.product-list.grid-block
.small-8.grid-content.text-center
%h4= product.name.titlecase
- if size = @product_sizes[product.id]
= link_to size['short_desc'], product, class: 'hollow button tiny'
%small= size['price']
祝你好运!
这篇关于如何从自定义SQL查询中提取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文