簡體   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