Specifying column name in a “references” migration

For Rails 5+ Initial Definition: If you are defining your Post model table, you can set references, index and foreign_key in one line: t.references :author, index: true, foreign_key: { to_table: :users } Update Existing: If you are adding references to an existing table, you can do this: add_reference :posts, :author, foreign_key: { to_table: :users } … Read more

Rails Migrations: tried to change the type of column from string to integer

I quote the manual about ALTER TABLE: A USING clause must be provided if there is no implicit or assignment cast from old to new type. What you need is: ALTER TABLE listings ALTER longitude TYPE integer USING longitude::int; ALTER TABLE listings ALTER latitude TYPE integer USING latitude::int; Or shorter and faster (for big tables) … Read more

Rails: PG::UndefinedTable: ERROR: relation “…” does not exist

So the issue is happening because CreateOrganizations migration is being run before CreateActioncodes is executed. CreateActioncodes is to be run first thereby ensuring that the action codes table exists. The order in which migrations are run is based on the time stamp of the migration – as indicated in the name of the file. 20141014183645_create_users.rb … Read more

Rails naming convention for join table

categories_products. Both plural. In lexical order. Quote: Unless the name of the join table is explicitly specified by using the :join_table option, Active Record creates the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of “customers_orders” because “c” … Read more

Add a reference column migration in Rails 4

Rails 4.x When you already have users and uploads tables and wish to add a new relationship between them. All you need to do is: just generate a migration using the following command: rails g migration AddUserToUploads user:references Which will create a migration file as: class AddUserToUploads < ActiveRecord::Migration def change add_reference :uploads, :user, index: … Read more