0

我的 Rails 应用程序包含两个名为 customer 和 order 的模型

class Customer < ActiveRecord::Base
      attr_accessible :name
    end

class Order < ActiveRecord::Base
  belongs_to :customer
  # attr_accessible :title, :body
end

在控制台中,我为客户模型创建了实例:

c=Customer.new(:name=>"Noa")

现在我想创建实例来订购引用“c”的模型我该怎么做?谢谢!

4

1 回答 1

1

最简单的方法是has_many在类内部Customer

class Customer < ActiveRecord::Base
   attr_accessible :name
   has_many :orders
end

然后您可以执行以下操作以将新订单关联到您的客户。

order = c.orders.build :attribute => 'value', # ...

您可以在此处找到有关如何在 Rails 中的对象之间建立关联的更多详细信息。

于 2013-03-10T13:14:13.597 回答