SSL setup: https://vimeo.com/209534466
rails g migration CreateJoinTableGameInvitesInvitees game_invites invitees
- Models linked together must be in alphabetical order when naming the migration file
- The columns can be given any names as long as they are correctly associated in the model file:
has_and_belongs_to_many :invitees, class_name: 'User', foreign_key: 'invitee_id', #the associated column and the alien model
join_table: 'game_invites_invitees', #name of the join table
association_foreign_key: 'game_invite_id' #the name of the domestic model in the join table
It is possible to declare a series of values that will be stored as an integer in the database (so declare the column as integer in the migration file). The series of values must be declared as an array using the enum method in the model. Some methods will be created automatically:
class Conversation < ActiveRecord::Base
enum status: [ :active, :archived ]
end
# Using enum will create some methods
conversation.active!
conversation.active? # => true
conversation.status # => "active"
# and some scopes
Conversation.active
Conversation.archived
Supposing we are using Postgre as a database, it only takes the following steps to use UUIDs as database IDs instead of incremental ones:
- Generate a migration:
rails g migration EnablePgcryptoExtension
- Modify the migration file to this:
class EnablePgcryptoExtension < ActiveRecord::Migration[5.1]
def change
enable_extension 'pgcrypto'
end
end
- Tell ActiveRecord that the new generator for IDs should be UUIDs:
#config/application.rb
config.generators do |g|
g.orm :active_record, primary_key_type: :uuid
end
NB: on uuid use for references and join tables
It is important to declare that a given model is using uuids when creating references or join tables, otherwise columns will store the values under wrong types in the DB:
- To make a reference with uuids, an example of migration, the
type: :uuid
flag must be added in the association column declaration:
class CreateMessages < ActiveRecord::Migration[5.1]
def change
create_table :messages, id: :uuid do |t|
t.references :player, type: :uuid
t.text :content
t.integer :turn_number
t.boolean :read
t.timestamps
end
end
end
- To create a join table between models using uuids:
class CreateJoinTableGameInvitesInvitees < ActiveRecord::Migration[5.1]
def change
create_join_table :game_invites, :invitees, column_options: {type: :uuid} do |t|
t.index [:game_invite_id, :invitee_id]
t.index [:invitee_id, :game_invite_id]
end
end
end