0

In my rails app i have a two models model customer (id, name, email) and cars(id, model, year).

customer has many cars cars belong to customer

1) I want to add the customer id field to the cars model. Will adding t.integer :customer_id to the migration file be enough?

2) Once added how would i start populating the said cars db?

(I just started on rails last week so would appreciate any help)

fox
  • 57
  • 7

2 Answers2

2

It is possible to add to your existing migration, but a more common workflow is to create a second migration to change an existing table.

Read about Rails Migrations for all the details.

  1. Make a migration

    rails generate migration add-customer-id-to-cars
    
  2. Add the correct code

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

    rake db:migrate
    
  4. Add the association in car.rb

    class Car < ActiveRecord::Base
      # Your Car code
    
      belongs_to :customer
    end
    
  5. Add the inverse association in your customer.rb

    class Customer < ActiveRecord::Base
      # Your Customer code
    
      has_many :cars
    end
    
yez
  • 2,368
  • 9
  • 15
  • Thank you! i will try both ways suggested here :) – fox Oct 18 '15 at 23:40
  • If i wanted to add a new car to a user i will have: @ car = @ customer.car.build ? in a new controller? – fox Oct 18 '15 at 23:53
  • You will have to set the relationship in the reverse, I will edit my post to demonstrate that. Then you can do `car = @customer.cars.build` – yez Oct 19 '15 at 00:03
1

(1) Yes. Though it would be more idiomatic to use t.references.

From Rails guides (adapted to context):

Using t.integer :customer_id makes the foreign key naming obvious and explicit. In current versions of Rails, you can abstract away this implementation detail by using t.references :customer instead.

You will also need to specify the associations in the model file.

class Customer < ActiveRecord::Base
  has_many :cars
end

class Car < ActiveRecord::Base
  belongs_to :customer
end

(2) You can use something like:

customer = Customer.find(id)
car = customer.cars.new
car.model = "some model"
car.save!
lorefnon
  • 12,875
  • 6
  • 61
  • 93