joeyk16
joeyk16

Reputation: 1415

has many through: not working

I have a has many through association thats not working.

Outfit has many products, and products has many outfits. Therefore im using has many through. Here is my set up.

outfit.rb

class Outfit < ActiveRecord::Base
  belongs_to :user
  has_many :outfit_products
  has_many :products, through: :outfit_products
end

product.rb

class Product < ActiveRecord::Base
  belongs_to :user
  belongs_to :category
  has_many :outfit_products
  has_many :outfits, through: :outfit_products
end

outfit_product.rb this is my middle table

class OutfitProduct < ActiveRecord::Base
  belongs_to :outfit
  belongs_to :product
end

Outfit.products should return all products associated with the outfit. The problem is its only showing 1 product. Even when i have 2 products linked to the same outfit. Please see below. I have 2 OutfitProduct objects with the same Outfit id and 2 different products.

2.1.2 :037 > OutfitProduct.all
  OutfitProduct Load (0.4ms)  SELECT "outfit_products".* FROM "outfit_products"
 => #<ActiveRecord::Relation [#<OutfitProduct id: 2, product_id: nil, outfit_id: 15, created_at: "2015-10-28 10:36:01", updated_at: "2015-10-28 10:36:01">, #<OutfitProduct id: 3, product_id: 26, outfit_id: 15, created_at: "2015-10-28 10:36:10", updated_at: "2015-10-28 10:36:10">]>

When i outfit.product only 1 product is showing? How do i make it show all products?

2.1.2 :038 > Outfit.find(15).products
  Outfit Load (0.3ms)  SELECT  "outfits".* FROM "outfits" WHERE "outfits"."id" = ? LIMIT 1  [["id", 15]]
  Product Load (0.2ms)  SELECT "products".* FROM "products" INNER JOIN "outfit_products" ON "products"."id" = "outfit_products"."product_id" WHERE "outfit_products"."outfit_id" = ?  [["outfit_id", 15]]
 => #<ActiveRecord::Associations::CollectionProxy [#<Product id: 26, title: "Lorem ipsum dolor1", price: #<BigDecimal:7fe94297a198,'0.59E2',9(27)>, description: "Lorem ipsum dolor sit amet, consectetur adipiscing...", created_at: "2015-09-22 11:16:37", updated_at: "2015-10-27 11:22:47", user_id: 53, image_file_name: "images.jpeg", image_content_type: "image/jpeg", image_file_size: 11331, image_updated_at: "2015-09-22 11:16:37", category_id: 20>]>
2.1.2 :039 >

Upvotes: 0

Views: 54

Answers (1)

Pavan
Pavan

Reputation: 33542

The problem is its only showing 1 product. Even when i have 2 products linked to the same outfit

Reason:

One of those outfit_products records has a product_id nil for the same outfit_id: 15, so when you do Outfit.find(15).products the one with product_id nil is omitted.

Upvotes: 1

Related Questions