【问题标题】:Rails 4 scope through belongs_to associationRails 4 范围通过 belongs_to 关联
【发布时间】:2016-02-01 19:11:45
【问题描述】:

我正在尝试根据其中一个父列中的值来确定子记录数组的范围。我正在尝试查找属于具有“捆绑包”类别的产品的所有 ShoppingCartItems。

我正在尝试使用acts_as_shopping_cart_gem

我的模型。

用户.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

产品.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>

【问题讨论】:

  • 你现在得到了什么?错误或没有返回记录或错误记录?
  • 错误:#<0x007fc0f40310d0>

标签: ruby-on-rails ruby-on-rails-4 scope rails-activerecord acts-as-shopping-cart


【解决方案1】:

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

我会这样做(广义范围):

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

注意,没有unless 语句 - 如果类别未传递给范围,则会引发 ArgumentError。

然后使用任何类别的范围:

ShoppingCartItem.by_category('Bundles')

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

Product.pluck(:category)

或类似的东西,如果它是用户界面的一部分。

【讨论】:

  • 是的,这太漂亮了。我将划分不同的类别,因此这是迄今为止处理此问题的最佳方法。谢谢!
【解决方案2】:

您范围内的类别字段与 ShoppingCartItem 相关吗?如果是这样,请尝试self.category.blank?。如果没有,只需删除除非语句。

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      • 2014-07-06
      • 1970-01-01
      • 2015-04-17
      • 1970-01-01
      • 2014-06-07
      相关资源
      最近更新 更多