lala
lala

Reputation: 2082

How do I set a join table's extra attribute?

These are my models

class Product
  has_many :line_items
  has_many :orders, :through => :line_items
end

class LineItem 
  belongs_to :order
  belongs_to :product

  validates :quantity, presence: true
end

class Order
    has_many :line_items
    has_many :products, :through => :line_items
end

I can do @order.products << @product to associate a product with an order, but I can't figure out how to also set the quantity in the join table.

Upvotes: 0

Views: 130

Answers (4)

TM.
TM.

Reputation: 3741

No need to join table's extra attribute, it's already there.

Order#line_items # will return all information's you need

But if you want return products in specific order with quantity try out following code.

First, add quantity as attr_accessor :quantity to Product.rb

Than, remove the following line has_many :products, :through => :line_items in Order.rb create products method instead

def products
  products_list = []
  line_items.each do |item|
    item.product.quantity = item.quantity
    products_list << item.product
  end
  products_list
end

order = Order.last
order.products # will return list of products with quantity attribute 

Upvotes: 0

Chris Schmitz
Chris Schmitz

Reputation: 8247

You could build up @line_item instead of the @product and then append that to @order's line items.

@line_item.quantity = 100
@line_item.product = Product.find(10)
@order.line_items << @line_item

Upvotes: 1

Baconator507
Baconator507

Reputation: 1747

You need to create the line item directly and specify its quantity and product.

Try something like this

@product = Product.find(1)
@order.line_items.create(product_id: @product.id, quantity: 100)

Upvotes: 0

cbron
cbron

Reputation: 4044

You want to do it by hand or through a form ?

If by hand you would just have to find the product in the LineItem's relation and update it:

x = @order.line_items.last
x.quantity = 2

edit: Baconator507's answer is the fastest

Upvotes: 0

Related Questions