This migration adds a receivenewsletter column to the users table. We want it to default to false for new users, but existing users are considered to have already opted in, so we use the User model to set the flag to true for existing users. Rails 3.1 makes migrations smarter by providing a new change method. This method is preferred for writing constructive migrations (adding. Script/generate can take table name. As far as I can tell script/generate will happily take the plural table name, at least in Rails 2.3. If the column names can not be derived from the table names, you can use the:column and:primarykey options. Rails will generate a name for every foreign key starting with fkrails followed by 10 characters which are deterministically generated from the fromtable and column. There is a:name option to specify a different name if needed.
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
There are many ways to add the foreign key column that's required by our has_many and belongs_to associations, and I want to take a moment to show you a couple more of them.
There are many ways to add the foreign key column that's required by our
has_many and belongs_to associations, and I want to take a moment to show you a couple more of them.
Without a foreign key constraint, we could create a comment with a
post_id field set to 999 , even if there was no record in the post table with an id of 999 . With a foreign key constraint, the database would prevent such a record from even being saved. Foreign key constraints help keep bad data from sneaking into your database.
Rails Migration Add Index
Note that the adapter for the SQLite database that Rails uses by default doesn't support foreign key constraints. Your migration will still work, and it's a good idea to get in the habit of adding the constraints in your migrations. But if you want the database to actually enforce the constraints, you'll need to switch to another database like MySQL or PostgreSQL.
If we know we're going to need an association when we're first creating a model, we can set the necessary columns up then, too.
![]()
![]() Add Numbers
You need to sign up for Treehouse in order to download course files.
Comments are closed.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |