首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >基于最低和最高价格的Rails获取产品

基于最低和最高价格的Rails获取产品
EN

Stack Overflow用户
提问于 2016-06-30 05:26:06
回答 1查看 347关注 0票数 0

我有一个rails应用程序,其中我有产品和它们的变体。

product.rb

代码语言:javascript
运行
复制
  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

代码语言:javascript
运行
复制
<% @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,只是为了让您知道我想要什么

请帮我找出解决办法

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-30 06:12:09

不管怎样,我自己想出来了,我需要加入到产品模型中,这样在我编写的范围内,Product.joins(:variants)就可以了

代码语言:javascript
运行
复制
scope :with_min_range, lambda { |min|
       where(" variants.price >= ?", "#{min.to_i}")
                         }

scope :with_max_range, lambda { |max|

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

它现在成功地获取记录的最低和最高价格,如果任何人可以给一个更好的答案,那么请!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38114590

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档