220 likes | 382 Views
Ruby on Rails. Your first app. So far we talked about…. DB migration Scaffolding Layouts Models Controllers … time to practice!. Add a second model. Create a Comment with properties: c ommenter: string body:text post:references Check db table: Run db migration.
E N D
Ruby on Rails Your first app
So far we talked about… • DB migration • Scaffolding • Layouts • Models • Controllers • … time to practice!
Add a second model • Create a Comment with properties: • commenter: string • body:text • post:references • Check db table: • Run db migration
Associating models • First check the Comment model • It belongs to a post • Then add the association to the Post model • A post can have many comments • Retrieve all comments using array: @post.comments • See more about Active record associations: http://guides.rubyonrails.org/association_basics.html
Adding a route for comments • Remember Home controller?? • We need to add a link to navigate and see comments • Which file do we need to edit? • Add nested resource:
Generate a controller • Now that we have a comments model, we will need to generate a controller • Use scaffold!
Still comments do not show… • Edit: /app/views/posts/show.html.erb
Change the comments controller Still we do not see the comments we create..
Showing comments • Which file do we need to edit??
Refactoring • Make app/views/posts/show.html.erbsmaller • Hints: • Create the fileapp/views/comments/_comment.html.erb. Put comments show part into it. Add a render statement in show.html.erb • Create: app/views/comments/_form.html.erb. Add the proper render statement to show.html.erb
Deleting comments • Edit: _comments.html.erb • Add the delete action to controller:
Deleting associated objects • If you delete a post then its associated comments will also need to be deleted.
Security • use the Rails http_basic_authenticate_with method