Skip to content

Instantly share code, notes, and snippets.

@puneetpandey

puneetpandey/my-habtm.rb

Last active Aug 29, 2015
Embed
What would you like to do?
#{PATH_TO_APP}$ rails g model Person name:string email:string
#{PATH_TO_APP}$ rails g model Community name:string description:text
class Person < ActiveRecord::Base
has_and_belongs_to_many :communities
end
class Community < ActiveRecord::Base
has_and_belongs_to_many :persons
end
class CreatePeople < ActiveRecord::Migration
def change
create_table :people do |t|
t.string :name, null: false
t.string :email, null: false
t.timestamps
end
end
end
class CreateCommunities < ActiveRecord::Migration
def change
create_table :communities do |t|
t.string :name, null: false
t.text :description
t.timestamps
end
end
end
# {PATH_TO_APP}$ rails g migration CreateJoinTablePersonCommunity person community
# invoke active_record
# create db/migrate/20140708122358_create_join_table_person_community.rb
class CreateJoinTablePersonCommunity < ActiveRecord::Migration
def change
create_join_table :people, :communities, column_options: {null: true} do |t|
# t.index [:person_id, :community_id]
# t.index [:community_id, :person_id]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.