Skip to content

Instantly share code, notes, and snippets.

@shehaaz
Created December 15, 2015 05:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shehaaz/f5c54f5a2e57843052bc to your computer and use it in GitHub Desktop.
Save shehaaz/f5c54f5a2e57843052bc to your computer and use it in GitHub Desktop.
Rails Active record
create new project
$rails new active_record
create model
$rails g model Manufacturer name:string
generate the game model
$rails g model Game name:string manufacturer:references
$bundle exec rake db:migrate
$sqlite3 db/development.sqlite3
> .tables
> .schema manufacturers
> .schema games
$ rails console --sandbox
Loading development environment in sandbox (Rails 4.2.5)
Any modifications you make will be rolled back on exit
2.2.1 :001 > manufacturer = Manufacturer.create(name:'Sega')
=> #<Manufacturer id: 1, name: "Sega", created_at: "2015-12-15 05:14:52", updated_at: "2015-12-15 05:14:52">
2.2.1 :002 > game = Game.create(name: 'shinobi', manufacturer: manufacturer) //it knows that manufacturer key means the manufacturer_id
=> #<Game id: 1, name: "shinobi", manufacturer_id: 1, created_at: "2015-12-15 05:29:55", updated_at: "2015-12-15 05:29:55">
2.2.1 :003 > game.manufacturer_id
=> 1
2.2.1 :004 > game.manufacturer.name
=> "Sega"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment