【问题标题】:One to Many BD - foriegn key & updates - rails一对多数据库-外键和更新-rails
【发布时间】:2015-10-18 20:44:25
【问题描述】:

在我的 Rails 应用程序中,我有两个模型模型客户(ID、姓名、电子邮件)和汽车(ID、型号、年份)。

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

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

2) 添加后,我将如何开始填充上述汽车数据库?

(我上周刚开始使用 Rails,希望能提供任何帮助)

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

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

    阅读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
      

    【讨论】:

    • 谢谢!我会尝试这里建议的两种方式:)
    • 如果我想向用户添加一辆新车,我将拥有:@car = @customer.car.build ?在新的控制器中?
    • 您必须反向设置关系,我将编辑我的帖子来证明这一点。然后你可以做car = @customer.cars.build
    【解决方案2】:

    (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!
    

    【讨论】:

      猜你喜欢
      • 2021-05-19
      • 2014-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-21
      • 1970-01-01
      • 2021-10-25
      相关资源
      最近更新 更多