问题
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')
below is the code within my view
- @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
回答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']
Good luck!
来源:https://stackoverflow.com/questions/34541022/how-to-extract-values-from-a-custom-sql-query