Rails Foreign key

Foreign key

In rails, has_many, belongs_to can express 1:many relationship, but it doesn’t include foreign key in database.
foreigner(package) can introduce foreign key to rails database.

Change gem file

gem 'foreigner', '~> 1.6.1'

Please check latest version of foreigner

Install

bundle install

Table

members 1 : many events
We manage member event in table
members

id                integer
email             string
email_index_for   string
family_name       string
last_name         string

events

id                integer
member_id         integer  (foreign key)
type              string
date              datetime

Model

rails g model member
rails g model event

Migration Script

members


class CreateMembers < ActiveRecord::Migration def change create_table :events do |t| t.string :email t.string :email_index_for t.string :family_name t.string :last_name end end end [/ruby] events


class CreateEvents < ActiveRecord::Migration def change create_table :events do |t| t.references :member, null: false # foreign key t.string :type, null: false t.datetime :date end add_foreign_key :events, :members # members end end [/ruby]

Model

Member


class Member < ActiveRecord::Base has_many :events, dependent: :destroy end [/ruby] Events


class Event < ActiveRecord::Base belongs_to :member, foreign_key: ‘member_id’ end [/ruby] Destroy operation :destroy, :delete_all, :nullify foreign_key option : with _id