Ruby on Rails and Database Associations

I'm new to the Ruby world, and there is something I don't understand about defining associations between models. The question arises: where is the association saved?

For example, if I create a Customer model by doing:

generate model Customer name:string age:integer

      

and then i create the order model

generate model Order description:text quantity:integer

      

and then I set the association like this:

class Customer < ActiveRecord::Base
  has_many :orders
end

class Order < ActiveRecord::Base
  belongs_to :customer
end

      

I think there is something missing here, like a foreign key between two objects. How does it handle associations created with the has_many and belongs_to keywords?

thanks

+2


a source to share


2 answers


Whenever you create your order, you can:

generate model Order description:text quantity:integer customer:references

      

And it will automatically create a foreign key for you. The rails convention is that each row will have a primary key named "id" and the foreign key is the table it refers to, followed by an underscore and then an ID. Therefore, in this case, the table of orders will have the attribute "customer_id"

Since you've already created yours, you must create a new migration script that will add an integer column named customer_id to the orders table.



You do not want to change the existing migration. Just create a new one that will add the column.

class add_customer_id_to_orders < ActiveRecord::Migration
  def self.up
    add_column :orders, :customer_id, :integer
  end

  def self.down
    remove_column :orders, :customer_id
  end
end

      

Note. If you've already done something to create data in your database, it will result in some null foreign keys that you want to fix, or just delete and create new data.

+3


a source


You have to add a column (integer) to the orders table called "customer_id".



+1


a source







All Articles