开发者

Ruby on Rails and database associations

开发者 https://www.devze.com 2022-12-30 05:46 出处:网络
I\'m new to the Ruby world, and there is something unclear to me in defining associations between models. The question is: where is the association saved?

I'm new to the Ruby world, and there is something unclear to me in defining associations between models. The question is: where is the association saved?

For example, 开发者_高级运维if i create a Customer model by executing:

generate model Customer name:string age:integer

and then i create an Order model

generate model Order description:text quantity:integer

and then i set the association in the following way:

class Customer < ActiveRecord::Base
  has_many :orders
end

class Order < ActiveRecord::Base
  belongs_to :customer
end

I think here is missing something, for example the foreign key between the two entities. How does it handle the associations created with the keywords "has_many" and "belongs_to" ?

Thanks


Whenever you generate your order, you can do:

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

And it will automatically create the foreign key in the migration for you. The rails convention is that every row will have a primary key called "id", and the foreign key is the table it is referencing, followed by an underscore, then id. So in this case the orders table will have an attribute called "customer_id"

Since you've already generated yours, you should create a new migration script that adds an integer column called "customer_id" to your orders table.

You don't want to modify an existing migration. Just create a new one that adds 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, this is going to result in some null foreign keys, which you'll want to fix, or just delete and create new data.


You should add an (integer) column to your orders table, called 'customer_id'.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号