一对多BD - foriegn key&更新 - rails

时间:2015-10-18 20:44:25

标签: ruby-on-rails ruby

在我的rails应用程序中,我有两个型号的客户(id,名称,电子邮件)和汽车(id,型号,年份)。

客户有很多车 汽车属于客户

1)我想将客户ID字段添加到汽车模型中。将t.integer:customer_id添加到迁移文件中是否足够?

2)一旦添加,我将如何开始填充所述汽车db?

(我上周刚开始使用rails,所以非常感谢任何帮助)

2 个答案:

答案 0 :(得分:2)

可以添加到现有迁移中,但更常见的工作流程是创建第二次迁移以更改现有表。

了解所有细节Rails Migrations

  1. 进行迁移

    rails generate migration add-customer-id-to-cars
    
  2. 添加正确的代码

    class AddCustomerIdToCars < ActiveRecord::Migration
      def change
        add_column :cars, :customer_id, :integer
      end
    end
    
  3. 迁移

    rake db:migrate
    
  4. car.rb

    中添加关联
    class Car < ActiveRecord::Base
      # Your Car code
    
      belongs_to :customer
    end
    
  5. 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!