mardi 26 mai 2015

How to add associations to models in rails

I have three models

class SupplierVariant

  belongs_to  :supplier
  belongs_to  :variant

end

class Supplier

  has_many :variants, :through :supplier_variants

end

class Variant

end

Now I want to know, how to get supplier of a particular variant.I added an association has_one :supplier through: :supplier_variant in Variant class

but when I do the following query I get below mentioned error

p=Spree::Variant.find(384)

  Spree::Variant Load (1.2ms)  SELECT  "spree_variants".* FROM "spree_variants" WHERE "spree_variants"."deleted_at" IS NULL AND "spree_variants"."id" = ? LIMIT 1  [["id", 384]]
 => #<Spree::Variant id: 384, sku: "CHG137-Blue-XL", weight: #<BigDecimal:a396b38,'0.5E3',9(27)>, height: #<BigDecimal:a396a20,'0.5E2',9(27)>, width: #<BigDecimal:a3968e0,'0.45E2',9(27)>, depth: #<BigDecimal:a396778,'0.75E2',9(27)>, deleted_at: nil, is_master: false, product_id: 228, cost_price: #<BigDecimal:a3962c8,'0.9E3',9(27)>, position: 4, cost_currency: "INR", track_inventory: true, tax_category_id: 3, updated_at: "2015-05-25 05:58:19", stock_items_count: 4> 

p.supplier
**NoMethodError: undefined method `supplier' for #<Spree::Variant:0x0000000a3973a8>**

How to add proper associations in model folder in rails? and How to use them after we add it? Does applying join operation between tables depend on the associations we define in models?

Aucun commentaire:

Enregistrer un commentaire