我有一个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中,结果将是变体的最低价格范围将大于min的值,而在with_max_range中,结果将是变体的最高价格低于max的产品。
P.S -我在where查询中给出了variant_price,只是为了让您知道我想要什么
请帮我找出解决办法
发布于 2016-06-30 06:12:09
不管怎样,我自己想出来了,我需要加入到产品模型中,这样在我编写的范围内,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}")
}它现在成功地获取记录的最低和最高价格,如果任何人可以给一个更好的答案,那么请!
https://stackoverflow.com/questions/38114590
复制相似问题