繁体   English   中英

Rails 4作用域通过belongs_to关联

[英]Rails 4 scope through belongs_to association

我试图通过基于父列之一中的值的一系列子记录来确定范围。 我正在尝试查找属于“捆绑销售”类别的产品的所有ShoppingCartItems。

我正在尝试使用acts_as_shopping_cart_gem

我的模特。

User.rb

class User < ActiveRecord::Base
  has_many :shopping_carts, dependent: :destroy
end

ShoppingCart.rb

class ShoppingCart < ActiveRecord::Base
  acts_as_shopping_cart_using :shopping_cart_item
  belongs_to :user
  has_many :shopping_cart_items, dependent: :destroy
  has_many :products, through: :shopping_cart_items
end

Product.rb

class Product < ActiveRecord::Base
  has_many :shopping_cart_items,  dependent: :destroy
end

ShoppingCartItem.rb

class ShoppingCartItem < ActiveRecord::Base
  belongs_to :product,  dependent: :destroy

  scope :bundles,  ->  { 
    joins(:product).where('products.category = ?', 'Bundles') unless category.blank?
  }

end

我收到此错误:

> undefined local variable or method `category' for
> #<Class:0x007fc0f40310d0>

您的问题实际上很简单-在任何地方都没有定义category变量。

这就是我要做的(广义范围):

scope :by_category, lambda { |category|
  joins(:product).where(products: { category: category })
}

注意,没有unless语句-如果未将类别传递到范围,它将引发ArgumentError。

然后将范围用于任何类别:

ShoppingCartItem.by_category('Bundles')

为防止将空白类别传递到范围中,只需确保传递正确的字符串即可。 您可以创建类别的下拉列表:

Product.pluck(:category)

或类似的内容(如果它是用户界面的一部分)。

您范围内的类别字段是否与ShoppingCartItem有关? 如果是这样,请尝试self.category.blank? 如果不是这样,则只需删除除非声明。

也许您需要添加Category模型并添加以下关系:

class Product < ActiveRecord::Base
  has_many :shopping_cart_items,  dependent: :destroy
  belongs_to :category
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM