Are references and Foreign keys the same thing?


I'm getting confused, are references and foreign keys the same thing really?

Is there a good example on FKs? I'd like to see how it goes in practice, for example how deleting the parent record would delete any existing records depending on it, and also how to avoid that from occurring...



I'm getting confused, are references and foreign keys the same thing really?

Sort of. I suspect what you are actually wondering about are foreign key constraints (where the database enforces that each foo_id column does indeed contain the id of a row from the foos table. Rails doesn't provide anything builtin for doing this, although there are various plugins. The documentation for your database should provide information on how it handles foreign keys Fred

Hi, thanks Fred.

Yes you are right I'm after FK constraints. And I guess that a way to do that is for example using this in a migration file: execute "alter table user_images add constraint fk_wi_user foreign key (user_id) references users(id)"



Yeah now I checked about foreign key constraints for MySql:

I think I understand it a bit better now. Using references or something like t.integer :project_id help creating the relations between tables, and help with queries like SELECT * FROM projects WHERE user_id = 22;

The foreign key constrains help using those keys to keep DB data consistent for example. As I mentioned I was actually looking for ON DELETE CASCADE so that was missing on my constraint definition above. It should be:

execute "alter table tasks add constraint fk_projects foreign key (project_id) references projects(id) ON DELETE CASCADE"

To make this easier to do, you might consider writing yourself a little helper, such as

def foreign_key(foreign_table, foreign_column, primary_table, primary_column = :id)   execute "     alter table #{foreign_table.to_s}       add constraint fk_#{foreign_table.to_s}_#{foreign_column.to_s}       foreign key (#{foreign_column.to_s}) references #{primary_table.to_s} (#{primary_column.to_s})   " end

def delete_foreign_key(foreign_table, foreign_column)   execute "alter table #{foreign_table.to_s} drop constraint fk_#{foreign_table.to_s}_#{foreign_column.to_s}" end

so you can use it like

foreign_key :addresses, :person_id, :people delete_foreign_key :addresses, :person_id