2016-06-30 4 views
0

私には製品とそのバリエーションがあるレールアプリがあります。私は、製品の価格帯をフェッチ方法はレールは最小値と最大値に基づいて製品を取り出します

<% @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 %> 

index.html.erb

ある

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 

product.rbは今、あなたはで見ることができますproduct.rb私はwith_min_rangeの結果wのように価格に基づいて製品を取得したい私が持っている - 病気その変種の最低価格帯min の値よりも大きくなり、with_max_rangeに結果がその亜種の製品になります最高価格max

PS未満になる製品もクエリはちょうど私が

その解決策を見つけ出すために私を助けてください

答えて

0

は、とにかく、私はそれ以降となるようProduct.joins(:variants)製品のモデルに参加させるために必要な自分自身をそれを考え出したい何のアイデアを与えるためにどこでvariant_price与えられましたscのOPE私は誰もが、その後、より良い答えをしてください与えることができれば、それは今成功し、最小値と最大価格 に基づいてレコードをフェッチ

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

scope :with_max_range, lambda { |max| 

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

書かれました!

関連する問題