Vinoth
Vinoth

Reputation: 2439

Associations with ActiveRecords in Ruby on Rails

I am new to RoR. I have a basic doubt with establishing relationship between models. Lets take a simple example of Employee and Manager. Manager manages many employees and an employee belongs to one manager. At the schema level, i will have a managerid foreign key in the employee table.

class Employee < ActiveRecord::Base
  attr_accessible :employee_id, :employee_name, :manager_id
  belongs_to :manager
end

class Manager < ActiveRecord::Base
  attr_accessible :manager_id, :manager_name
  has_many :employeees
end

Once i specify such relationships in the model how can i ensure such data integrity is maintained in the database? I ran rake db:migrate command but it doesn't seem to affect anything in the database. What should i do to establish foreign key-primary key relationship between manager and employee table in the database? I am using sql-server 2008.

Thanks in advance.

Upvotes: 0

Views: 95

Answers (2)

sockmonk
sockmonk

Reputation: 4255

This isn't provided directly in rails because the implementation must be database specific. The foreigner gem adds a 'add_foreign_key' command for migrations that works for mysql, postgres and sql_lite; the oracle_enhanced adapter supplies it for Oracle.

If you can't find a gem that works for sql server and your adapter doesn't provide it, you can always add a raw sql statement to your migration:

sql = "CREATE FOREIGN KEY ..."
execute(sql)

If you're doing this a lot, you might want to wrap it up in your own add_foreign_key helper, preferably using the same API as the above gems use.

Upvotes: 1

th3sku11
th3sku11

Reputation: 76

Have you edited the migration files created when you generated the models? In the employee migration you'll need to specify the foreign key like so:

class CreateEmployees < ActiveRecord::Migration
  def change
    create_table :employees do |t|
      t.string :manager_name
      t.integer :manager_id
    end
  end
end

You can find the migration files in the db/migrations folder. You can roll back your migration to the point before creating the employees table and modify the create_table block or you can create a new migration to add the foreign key.

Upvotes: 1

Related Questions