Is there anything we could add to the following migration to ensure that actions will only be able to reference projects that actually exist in our system?
class CreateActions < ActiveRecord::Migration
def change
create_table :actions do |t|
t.string :title
t.references :project
t.timestamps null: false
end
add_index :actions, :project_id
end
end
The migration could include a foreign key constraint that would enforce the
Action
-> Project
relationship to ensure an Action
can never point to a
non-existent Project.
class CreateActions < ActiveRecord::Migration
def change
create_table :actions do |t|
t.string :title
t.references :project
t.timestamps null: false
end
add_index :actions, :project_id
add_foreign_key :actions, :projects
end
end
Check out [our post on Rails Foreign Keys][] for more detail and tips on implementing foreign keys in your rails app.
Note Rails 4.2 has native support for foreign keys, but for prior versions of Rails you'll need to include the [Foreigner Gem][].
[our post on Rails Foreign Keys]: https://robots.thoughtbot.com/referential-integrity-with-foreign-keys [Foreigner Gem]: https://github.com/matthuhiggins/foreigner
Return to Flashcard Results