Rails 根据最低和最高价格获取产品
Rails fetch products based on minimum and maximum price
我有一个 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
只是为了让你知道我想要什么
请帮我想出解决办法
无论如何我自己想出来我需要加入产品模型以便 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}")
}
现在可以根据最低价和最高价成功获取记录
如果有人能给出更好的答案,那么请!
我有一个 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
只是为了让你知道我想要什么
请帮我想出解决办法
无论如何我自己想出来我需要加入产品模型以便 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}")
}
现在可以根据最低价和最高价成功获取记录 如果有人能给出更好的答案,那么请!