Created
March 8, 2011 19:07
-
-
Save Gregg/860804 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
# Objective | |
Refactor the Users#follow action and move code into the User model. Create the follow method in the User model. | |
# Before | |
class UsersController < ApplicationController | |
def follow | |
@user = User.find(params[:id]) | |
if current_user.followings.where(:followed_user_id => @user.id).present? | |
redirect_to @user | |
else | |
current_user.followings.create(:followed_user => @user) | |
redirect_to root_url | |
end | |
end | |
end | |
class User < ActiveRecord::Base | |
has_many :followings | |
# This method should check to see if a user is already being followed. | |
# Create the model if not, otherwise return false | |
# def follow(user) | |
end | |
# After | |
class UsersController < ApplicationController | |
def follow | |
@user = User.find(params[:id]) | |
if current_user.follow(@user) | |
redirect_to root_url | |
else | |
redirect_to @user | |
end | |
end | |
end | |
class User < ActiveRecord::Base | |
has_many :followings | |
def follow(user) | |
unless followings.where(:followed_user_id => @user.id).present? | |
followings.create(:followed_user => @user) | |
else | |
false | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment