2016-06-30 1 views
0

제품과 그 변형이있는 레일 앱이 있습니다.레일은 최소 및 최대 가격을 기준으로 제품을 가져옵니다.

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 결과는 w입니다. 병이 그 변종 '최저 가격 범위 min 의 값보다 커야되고 with_max_range의 결과는 그 변종 제품이 될 것'최대 1 가격 max

PS보다 적은 것이다 제품 수 - 내가 가지고있는 를 Where 쿼리에 variant_price 주어진 것은 단지 내가

난 제품 모델에 참여하기 위해 필요한

답변

0

가 어쨌든 내가 나 자신을 알아 낸 그 해결책을 알아 내기 위해 제발 도와주세요 원하는 당신에게 아이디어를주고 그 후 그 Product.joins(:variants) 때문에 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}") 
         } 

작성!

관련 문제