Created
July 17, 2013 14:16
-
-
Save Papillard/6020934 to your computer and use it in GitHub Desktop.
Refactor the code to delegate logic to the model
This file contains 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
# Model | |
class User < ActiveRecord::Base | |
has_many :followings | |
def follow(user) | |
self.followings.create(:followed_user => user) unless self.followings.where(:followed_user_id => user.id).present? | |
end | |
end | |
# Controller | |
class UsersController < ApplicationController | |
def follow | |
@user = User.find(params[:id]) | |
if current_user.follow(@user).nil? | |
redirect_to @user | |
else | |
redirect_to root_url | |
end | |
end | |
end |
This file contains 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
# Model | |
class User < ActiveRecord::Base | |
has_many :followings | |
end | |
# Controller | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment