How to extract values from a custom SQL query

我是研究僧i 提交于 2019-12-12 03:14:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!