views:

20

answers:

3

Currently I have an Order class. each order has 1 to infinite number of items. the number of items is not known until run time. since there is no field type of Array in active record / rails, how do you create a variable number of columns?

The only way I can think of is to specify a bunch of ticket columns ahead of time; but is very inflexible and inefficient:

class CreateOrders < ActiveRecord::Migration
  def self.up
    t.integer :ticket_id, :ticket_id, :ticket_id, :ticket_id, :ticket_id
    t.decimal :total
    t.timestamps
  end

  def self.down
    drop_table :orders
  end
end
+2  A: 

Typically, a 3rd Normal form of database table won't have variable number of columns.

What you have can be 2 tables, one for order, and it "has many" line items, so this LineItem model will have entries stored in the line_items table, with each record having a product_id and quantity, and each LineItem "belongs to" an Order. (having a order_id, or line_item.order referring to the order it belongs to).

動靜能量
How would I set up the order tablet to accept 1 or more line_items?
Anthony H
A: 

You have to use another table called items which will have a order_id column.Hence many items can be associated to a single order. In other words an order can have many items.

Read this article explaining order having many invoices(in your case items).

Deepak N
A: 

As has been said, you want to model this as a belongs_to / has_many relationship.

class CreateOrders < ActiveRecord::Migration
  def self.up
    t.decimal :total
    t.timestamps
  end

  def self.down
    drop_table :orders
  end
end

class CreateItems < ActiveRecord::Migration
  def self.up
    t.integer :ticket_id
    t.integer :order_id
    t.timestamps
  end

  def self.down
    drop_table :items
  end
end

class Order < ActiveRecord::Base
  has_many :items, :dependent => "destroy"
end

class Item < ActiveRecord::Base
  belongs_to :order
end

Order.all.each do |order|
  puts "Order " + order + " has items :"
  order.items.each { |item| puts "  " + item }
end
Collin