jake
jake

Reputation: 1665

Ruby on Rails - How to Create Foreign Key in Scaffold

I'm pretty new to rails, so there might be a simple answer. I'm trying to add a "user_category" column to my "users" table that refers to a "user_categories" table. I tried the following:

rails generate migration add_user_category_to_users user_category:integer

and then...

rails generate scaffold User_Category title:string description:text

But on rake db:migrate I get the following error:

==  CreateUserCategories: migrating ===========================================
-- create_table(:user_categories)
rake aborted!
An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: table "user_categories" already exists: CREATE TABLE "user_categories" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255), "description" text, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL) 

Any help would be appreciated.

Upvotes: 3

Views: 6020

Answers (1)

Dan K.K.
Dan K.K.

Reputation: 6094

The Active Record way claims that intelligence belongs in your models, not in the database. As such, features such as triggers or foreign key constraints, which push some of that intelligence back into the database, are not heavily used.

Validations such as validates :foreign_key, :uniqueness => true are one way in which models can enforce data integrity. The :dependent option on associations allows models to automatically destroy child objects when the parent is destroyed. Like anything which operates at the application level, these cannot guarantee referential integrity and so some people augment them with foreign key constraints in the database.

Although Active Record does not provide any tools for working directly with such features, the execute method can be used to execute arbitrary SQL. You could also use some plugin like foreigner which add foreign key support to Active Record (including support for dumping foreign keys in db/schema.rb).

http://guides.rubyonrails.org/migrations.html

Upvotes: 5

Related Questions