NothingToSeeHere
NothingToSeeHere

Reputation: 2373

Rails 4 scope through belongs_to association

I am trying to scope through an array of child records based on a value in one of the parent columns. I am trying to find all the ShoppingCartItems that belong to a Product with a category "Bundle."

I am trying to use acts_as_shopping_cart_gem

My Models.

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

I am getting this error:

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

Upvotes: 1

Views: 1236

Answers (3)

Andrey Deineko
Andrey Deineko

Reputation: 52377

Your problem is actually straight forward - there is nowhere you defined the category variable.

This is how I would do that (generalized scope):

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

Note, there is no unless statement - if the category is not passed to scope, it will raise the ArgumentError.

Then use the scope for any category:

ShoppingCartItem.by_category('Bundles')

To prevent the blank category to be passed into scope, just make sure you pass the right string. You can create a dropdown of categories:

Product.pluck(:category)

or something similar, if it is a part of user interface.

Upvotes: 1

Konstantine Kalbazov
Konstantine Kalbazov

Reputation: 2673

Maybe you need to add Category model and add this relation:

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

Upvotes: 0

Jonas Meinerz
Jonas Meinerz

Reputation: 622

The category field on your scope regards the ShoppingCartItem? If so, try self.category.blank?. If not, just remove the unless statement.

Upvotes: 0

Related Questions