Week 07 Active Record Associations - Code-the-Dream-School/rails-guidebook GitHub Wiki
Week | Topic | Learning Objectives | Key Resources |
---|---|---|---|
7 | Active Record Associations |
|
Lesson Materials - See Coding Assignment Coding Assignment |
- 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.
-
Branch Setup
- Create a new branch
lesson7_1
fromlesson6
- Create a new branch
-
Step 1: Adjustments to Appearance
- Add
root 'forums#index'
toconfig/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
- Add
-
Step 2: Creating the Models
- Generate models for
post
andsubscription
- Run
bin/rails db:migrate
- Update model files (
forum.rb
,post.rb
,subscription.rb
,user.rb
) with associations - Test model associations in Rails console
- Generate models for
-
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
)
- Define routes in
-
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
andedit.html.erb
for posts - Update
app/views/forums/show.html.erb
to display posts and add new post link
- Create
-
Testing and Error Handling
- Test CRUD operations for posts
- Override form URL in
_form.html.erb
for nested routes - Verify all functionalities work correctly
-
Checking for Understanding
- Answer questions in
lesson7-questions.txt
(see below)
- Answer questions in
-
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
- Add and commit changes to
-
before_action is the method used to run code before controller actions. To affect all controllers, you can place it in ApplicationController.
-
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.
-
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.
-
The Subscription instance methods are user and forum. These allow you to access the associated User and Forum objects, respectively.
-
Methods available to instances of User are subscriptions, posts, and forums. These methods return collections of the associated models.
-
user.subscriptions returns an ActiveRecord::Associations::CollectionProxy. The attribute set in new_subscription is user_id, which gets the value from the user instance.
-
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" = ?
-
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).
-
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.
-
Every action method must either render a view (e.g., render :new) or redirect to another URL (e.g., redirect_to @forum).