导轨 - 通过控制台
问题描述:
参考模型实例第二模型实例正确的方式
我的Rails应用程序包含一个名为客户和订单导轨 - 通过控制台
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” 我该怎么做? 谢谢!
答
最简单的方法是有一个has_many
的Customer
类中:
class Customer < ActiveRecord::Base
attr_accessible :name
has_many :orders
end
,然后你可以做以下到一个新的,以你的客户联系起来。
order = c.orders.build :attribute => 'value', # ...
你可以找到here如何建立对象之间的关联在Rails的更多细节。