在我的rails应用程序中,我有两个型号的客户(id,名称,电子邮件)和汽车(id,型号,年份)。
客户有很多车 汽车属于客户1)我想将客户ID字段添加到汽车模型中。将t.integer:customer_id添加到迁移文件中是否足够?
2)一旦添加,我将如何开始填充所述汽车db?
(我上周刚开始使用rails,所以非常感谢任何帮助)
答案 0 :(得分:2)
可以添加到现有迁移中,但更常见的工作流程是创建第二次迁移以更改现有表。
了解所有细节Rails Migrations。
进行迁移
rails generate migration add-customer-id-to-cars
添加正确的代码
class AddCustomerIdToCars < ActiveRecord::Migration
def change
add_column :cars, :customer_id, :integer
end
end
迁移
rake db:migrate
在car.rb
class Car < ActiveRecord::Base
# Your Car code
belongs_to :customer
end
在customer.rb
class Customer < ActiveRecord::Base
# Your Customer code
has_many :cars
end
答案 1 :(得分:1)
(1)是的。虽然使用t.references
会更加惯用。
来自Rails guides(适应上下文):
使用t.integer:customer_id使外键命名明显 明确。在当前版本的Rails中,您可以抽象出来 使用t.references实现细节:客户代替。
您还需要在模型文件中指定关联。
class Customer < ActiveRecord::Base
has_many :cars
end
class Car < ActiveRecord::Base
belongs_to :customer
end
(2)你可以使用类似的东西:
customer = Customer.find(id)
car = customer.cars.new
car.model = "some model"
car.save!