Skip to content

Instantly share code, notes, and snippets.

@Papillard
Created July 17, 2013 14:16
Show Gist options
  • Save Papillard/6020934 to your computer and use it in GitHub Desktop.
Save Papillard/6020934 to your computer and use it in GitHub Desktop.
Refactor the code to delegate logic to the model
# 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
# 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