开发者

Is there a more eloquent way of creating a table that has a variable number of columns: Active Record & Rails 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开发者_StackOverflow 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


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).


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).


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜