Skip to content

Instantly share code, notes, and snippets.

@mnishiguchi
Last active June 29, 2016 15:36
Show Gist options
  • Select an option

  • Save mnishiguchi/f2779649b3eec5fdbb7e to your computer and use it in GitHub Desktop.

Select an option

Save mnishiguchi/f2779649b3eec5fdbb7e to your computer and use it in GitHub Desktop.
Rails - has_many & belongs_to関係を既存のモデルに追加 ref: http://qiita.com/mnishiguchi/items/35e40ab46ef02d095ce0
class AddRoomToMovings < ActiveRecord::Migration
def change
add_reference :movings, :room, index: true, foreign_key: true
end
end
class AddMovingToRooms < ActiveRecord::Migration
def change
add_reference :rooms, :moving, index: true, foreign_key: true
end
end
class CreateMovingRooms < ActiveRecord::Migration
def change
create_table :moving_rooms do |t|
t.integer :moving_id
t.integer :room_id
t.timestamps null: false
end
end
end
class AddIndexToMovingRooms < ActiveRecord::Migration
def change
add_index :moving_rooms, :moving_id
add_index :moving_rooms, :room_id
add_index :moving_rooms, [:moving_id, :room_id], unique: true
end
end
class Moving < ActiveRecord::Base
...
has_many :moving_rooms, dependent: :destroy
has_many :rooms, through: :moving_rooms
...
class Moving < ActiveRecord::Base
...
has_many :moving_rooms, dependent: :destroy
has_many :rooms, through: :moving_rooms
...
class Room < ActiveRecord::Base
...
has_many :moving_rooms, dependent: :destroy
has_many :movings, through: :moving_rooms
...
$ rails destroy migration add_moving_to_rooms moving:references
invoke active_record
remove db/migrate/20150725142845_add_moving_to_rooms.rb
$ rails destroy migration add_room_to_movings room:references
invoke active_record
remove db/migrate/20150725142417_add_room_to_movings.rb
$ bundle exec rake db:drop
$ bundle exec rake db:create
$ bundle exec rake db:migrate
$ bundle exec rake db:seed
rails g model MovingRoom moving_id:integer room_id:integer
class Moving < ActiveRecord::Base
...
has_many :rooms, dependent: :destroy
...
class MovingRoom < ActiveRecord::Base
belongs_to :moving
belongs_to :room
end
class Room < ActiveRecord::Base
...
belongs_to :moving
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment