我的Rails应用程序包含两个名为customer和order的模型
class Customer < ActiveRecord::Base
attr_accessible :name
end
class Order < ActiveRecord::Base
belongs_to :customer
# attr_accessible :title, :body
end
在控制台中,我创建了customer模型的实例:
c=Customer.new(:name=>"Noa")
现在我想创建引用"c“的instance to order模型,我该怎么做呢?谢谢!
发布于 2013-03-10 21:14:14
最简单的方法是在Customer
类中包含一个has_many
:
class Customer < ActiveRecord::Base
attr_accessible :name
has_many :orders
end
然后,您可以执行以下操作将新订单与您的客户相关联。
order = c.orders.build :attribute => 'value', # ...
您可以在here中找到有关如何在Rails中的对象之间建立关联的更多细节。
https://stackoverflow.com/questions/15321738
复制相似问题