I’ve already created my models and have gone through several migrations. Now, I want to setup has_many :books in Subject and belongs_to :subject in Book. I’ve added those to the .rb files, but I’m still allowed to save a book with a subject_id that does not exist. I’m expecting a FK constraint violation.
Must I create a migration file for this? If so, how do I do it?
you can generate a lone migration file (without a model) by using
script/generate migration, orrails g migrationfor rails 2 / 3 respectively. You can then include the constraints to the self.up method in the migration file and run them on the database using a rake db:migrate.Note however that unless you’re planning on handling the error using your own custom code to catch ActiveRecord errors you’re probably better off using rails validations to ensure that associations are present. i.e.
app/models/book.rb
EDIT: If you want to add foreign keys to your database then you will have to know how to do this using the command set relevant to your database engine (e.g. for MySQL http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html). Since rails is designed to work with databases that don’t support foreign keys there are no built in functions in the rails migration toolkit which can help you with this process.
as a rough outline of what you’ll need in your migration (using MySQL specific syntax):