Rails根据最低和最高价格获取产品

时间:2016-06-30 05:26:07

标签: ruby-on-rails ruby fetch

我有一个rails应用程序,其中我有产品及其变体。

product.rb

  class Product < ActiveRecord::Base
    has_many :variants

    scope :with_min_range, lambda { |min|
       where(" (variant_price) >= ?", "#{min.to_i}")
                         }
    scope :with_max_range, lambda { |max|

                           where("(variant_price) <= ?", ["#{max.to_i}"])
                         }

    def price_range
        return @price_range if @price_range
        return @price_range = ['N/A', 'N/A'] if active_variants.empty?
        @price_range = active_variants.minmax {|a,b| a.price <=> b.price }.map(&:price)
      end

   def price_range?
      !(price_range.first == price_range.last)
   end

    end

我获取产品价格范围的方式是

index.html.erb

<% @products.each do |product| %>
    <figcaption>
      <h4 class="aa-product-title"><%= link_to product.name, product_path(product) %></h4>
       <span class="aa-product-price"><%= number_to_currency(product.price_range.first, :locale => :in ) %>
         <% if product.price_range? %>
                                   to
          <%= number_to_currency(product.price_range.last, :locale => :in) %>
          <% end %></span>
     </figcaption>
<% end %>

现在你可以在product.rb中看到我想根据价格获取产品,这样在with_min_range中,结果将是其变体&#39;最低价格范围将大于min的价值 在with_max_range中,结果将是其变体&#39;最高价格将低于max

P.S - 我在where查询中提供variant_price只是为了让您了解我想要的内容

请帮我弄清楚其解决方案

1 个答案:

答案 0 :(得分:0)

无论如何我自己想出来我需要在产品模型中加入,以便在我写的范围之后Product.joins(:variants)

scope :with_min_range, lambda { |min|
       where(" variants.price >= ?", "#{min.to_i}")
                         }

scope :with_max_range, lambda { |max|

                           where("variants.price <= ?", "#{max.to_i}")
                         }

它现在可以根据最低和最高价格成功获取记录 如果有人能给出更好的答案那么请!

相关问题