rails:活动记录查询范围内的条目和包含在

yr9zkbsy  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(377)

我正在为一个 checkout 过程的发货实现工作。
我的应用程序有购物车,购物车物品,订单和订单物品。
所有物品的重量和大小都在数据库中,我计算订单和购物车模型中的总重量。我还有一个航运服务模型,每个航运服务都有weightmin和weightmax+postzone和land(country)模型。
现在我想在购物车页面上只显示符合购物车或订单重量的运输服务。
我想我的手推车控制器应该是这样的:

class CartsController < ApplicationController
def show
    @cart = Cart.find(params[:id])
    @lands = Land.find(:all)
    @shippingservices = Shippingservice.where('@cart.total_weight BETWEEN ? AND ?', :weightmin, :weightmax)
end

我的购物车型号是:

class Cart < ActiveRecord::Base
  attr_accessor :total_weight

  has_many :cart_items
  has_many :products, :through => :cart_items
  has_many :lands
  has_many :shipping_services, :through => :postzones

  def total_weight
    cart_items.inject(0) {|sum, n| n.weight * n.amount + sum}
  end
end

我的土地模型是

class Land < ActiveRecord::Base
  has_many :shippingservices, :through => :postzones
  has_many :postzones
  has_many :carts
end

我的配送服务模式是:

class Shippingservice < ActiveRecord::Base
  has_many :lands, :through => :postzones
  has_many :postzones
  has_many :carts
  has_many :orders
end

我的postzone模型是:

class Postzone < ActiveRecord::Base
  belongs_to :shippingservice
  belongs_to :land
end

postzone表具有用于lands和shipping服务的外键。
后面我想实现两个选择器字段:一个用于ship\ to\ u countries,另一个用于shipping\ u services,第二个选择器只填充与第一个选择器中选择的条目相关的条目。
我已经在carts\u控制器内工作了:

@shippingservices = Shippingservice.includes(:lands, :postzones).where('postzones.land_id = ?', Land.first.id)

它只将特定国家的运输服务加载到第二个选择器中。但我不知道如何将与weight和postzone相关的两个where子句组合到一个查询中。
非常感谢您的帮助!
先谢谢你。

wmomyfyw

wmomyfyw1#

方法 total_weight 是在模型中定义的ruby方法 Cart 则不能在sql语句中调用此方法。
您需要计算sql语句中的总权重。
你应该试试

@shippingservices = Shippingservice.joins(carts: :cart_items).where(
  '(cart_items.weight * cart_items.amount) BETWEEN ? AND ?', :weightmin, :weightmax
)

我没试过,但我觉得应该有用:)

相关问题