Week 07 Active Record Associations - Code-the-Dream-School/rails-guidebook GitHub Wiki

Week Topic Learning Objectives Key Resources
7 Active Record Associations
  • Build a simple Rails application, without scaffolding
  • Implement one to many and many to many associations
  • Implement basic access control
  • Practice modifying routes, controllers, models, and views
  • Understand adding association methods to models
  • Practice use of the Rails console for CRUD operations
Lesson Materials - See Coding Assignment

Coding Assignment

Overview

  • Introduction
    • Understanding associations in databases using Active Record ORM.
    • One-to-many association between forums and posts.
    • Many-to-many-through association between users and forums using a join table (subscriptions).
    • One-to-many association between users and posts.
  • Step 1: Adjustments to Appearance
    • Add a navigation bar.
    • Set the default page to forums view.
    • Modify application_controller.rb to set the current user.
    • Add basic CSS for navigation bar styling.
    • Update application.html.erb to include the navigation bar.
  • Step 2: Creating the Models
    • Generate Post and Subscription models.
    • Update models with appropriate associations.
    • Create sample records using Rails console to understand associations.
  • Step 3: Creating Routes and the Post Controller
    • Update routes to include posts and subscriptions.
    • Generate the posts controller and add methods for CRUD operations.
    • Implement access control and instance variable setting in the posts controller.
  • Step 4: Posts Views
    • Create views for showing, creating, and editing posts.
    • Use partials for common elements like post display and form.
    • Update forums show view to display posts and add a link for creating new posts.
    • Override Rails default URL behavior for form submission.
  • Checking for Understanding
    • Answer questions in lesson7-questions-txt.
  • Submitting Your Work
    • Commit and push changes to GitHub.
    • Create a pull request and submit the link.

Assignment Rubric

  1. Branch Setup

    • Create a new branch lesson7_1 from lesson6
  2. Step 1: Adjustments to Appearance

    • Add root 'forums#index' to config/routes.rb
    • Verify default page change to forums view
    • Modify app/controllers/application_controller.rb for user session handling
    • Remove duplicate code from app/controllers/user.rb
    • Add styling to app/assets/stylesheets/application.css
    • Add navigation bar to app/views/layouts/application.html.erb
  3. Step 2: Creating the Models

    • Generate models for post and subscription
    • Run bin/rails db:migrate
    • Update model files (forum.rb, post.rb, subscription.rb, user.rb) with associations
    • Test model associations in Rails console
  4. Step 3: Creating Routes and the Post Controller

    • Define routes in config/routes.rb
    • Generate posts controller with actions
    • Add before_action callbacks in posts controller
    • Implement controller methods (create, new, edit, show, update, destroy)
  5. Step 4: Posts Views

    • Create _post.html.erb partial
    • Implement show.html.erb for posts
    • Create _form.html.erb partial for post forms
    • Implement new.html.erb and edit.html.erb for posts
    • Update app/views/forums/show.html.erb to display posts and add new post link
  6. Testing and Error Handling

    • Test CRUD operations for posts
    • Override form URL in _form.html.erb for nested routes
    • Verify all functionalities work correctly
  7. Checking for Understanding

    • Answer questions in lesson7-questions.txt (see below)
  8. Submitting Your Work

    • Add and commit changes to lesson7_1 branch
    • Push lesson7_1 branch to GitHub
    • Create pull request
    • Submit link to the pull request in the homework submission form

Lesson7-questions.txt Responses

  1. before_action is the method used to run code before controller actions. To affect all controllers, you can place it in ApplicationController.

  2. The two important files created are the migration file and the model file (subscription.rb). After generating the model, you need to run bin/rails db:migrate.

  3. The migration creates a subscriptions table. Column names are id (primary key), forum_id (foreign key), user_id (foreign key), and priority. Foreign keys (forum_id, user_id) link to primary keys in other tables, ensuring referential integrity.

  4. The Subscription instance methods are user and forum. These allow you to access the associated User and Forum objects, respectively.

  5. Methods available to instances of User are subscriptions, posts, and forums. These methods return collections of the associated models.

  6. user.subscriptions returns an ActiveRecord::Associations::CollectionProxy. The attribute set in new_subscription is user_id, which gets the value from the user instance.

  7. To retrieve all the user's posts for a specific forum:

    user.posts.where(forum: forum)

    The SQL executed is similar to:

    SELECT "posts".* FROM "posts" WHERE "posts"."user_id" = ? AND "posts"."forum_id" = ?
  8. The security risk is that someone could potentially delete posts they don’t own. To prevent this, the code should include before_action :authenticate_user! to ensure the user is logged in, and an additional check to verify the user owns the post (@post.user == current_user).

  9. Nesting routes under forum changes the URL structure, including the forum ID in the path (e.g., /forums/:forum_id/subscriptions). The additional hash key in params is :forum_id. Routes like index and show for subscriptions are unaffected by the nesting.

  10. Every action method must either render a view (e.g., render :new) or redirect to another URL (e.g., redirect_to @forum).

⚠️ **GitHub.com Fallback** ⚠️