【发布时间】:2015-10-18 20:44:25
【问题描述】:
在我的 Rails 应用程序中,我有两个模型模型客户(ID、姓名、电子邮件)和汽车(ID、型号、年份)。
客户有很多车 汽车属于客户
1) 我想将客户 ID 字段添加到汽车模型。将 t.integer :customer_id 添加到迁移文件就足够了吗?
2) 添加后,我将如何开始填充上述汽车数据库?
(我上周刚开始使用 Rails,希望能提供任何帮助)
【问题讨论】:
标签: ruby-on-rails ruby
在我的 Rails 应用程序中,我有两个模型模型客户(ID、姓名、电子邮件)和汽车(ID、型号、年份)。
客户有很多车 汽车属于客户
1) 我想将客户 ID 字段添加到汽车模型。将 t.integer :customer_id 添加到迁移文件就足够了吗?
2) 添加后,我将如何开始填充上述汽车数据库?
(我上周刚开始使用 Rails,希望能提供任何帮助)
【问题讨论】:
标签: ruby-on-rails ruby
可以添加到现有迁移中,但更常见的工作流程是创建第二个迁移以更改现有表。
阅读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
【讨论】:
car = @customer.cars.build
(1) 是的。虽然使用t.references 会更惯用。
来自Rails guides(适应上下文):
使用 t.integer :customer_id 使外键命名显而易见,并且 明确的。在当前版本的 Rails 中,您可以抽象出这个 使用 t.references :customer 代替实现细节。
您还需要在模型文件中指定关联。
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!
【讨论】: