Created
July 17, 2014 17:32
-
-
Save davidpots/0e8ca1f940dc73d42b4a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Create an app: | |
rails new whatever | |
Generate some scaffolding: | |
rails generate scaffold User name:string | |
rails generate scaffold Item user_id:integer collection_id:integer name:string | |
rails generate scaffold Collection user_id:integer name:string | |
Migrate | |
rake db:migrate | |
Edit the model files for each. Make them look like this: | |
class CollectionsController < ApplicationController | |
belongs_to :user | |
has_many :items | |
end | |
class ItemsController < ApplicationController | |
belongs_to :user | |
has_and_belongs_to_many :collections | |
end | |
class UsersController < ApplicationController | |
has_many :items | |
has_many :collections | |
end | |
Now you can start your server: | |
rails s | |
And then you can create some records via these URLs. For now, a good demo is to create one user, some items, and a collection. Or do more. | |
localhost:3000/users | |
localhost:3000/items | |
localhost:3000/collections | |
Once you've done that, open up console: | |
rails c | |
And now you can do stuff like: | |
User.first # shows the first User | |
User.first.items # shows the first User's items | |
User.first.items.first.name # shows the first User's first item's name | |
Item.first # etc | |
Item.first.user | |
Item.first.user.name | |
Collection.first | |
Collection.first.user | |
Collection.first.user.name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment