Skip to content

Instantly share code, notes, and snippets.

@krisf
Created April 20, 2012 00:20
Show Gist options
  • Save krisf/2424980 to your computer and use it in GitHub Desktop.
Save krisf/2424980 to your computer and use it in GitHub Desktop.
#Theirs:
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
#Mine:
class UsersController < ApplicationController
def follow
@user = User.find(params[:id])
current_user.follow(@user) ? redirect_to root_url : redirect_to @user
end
end
#Theirs:
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
#Mine:
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
@jswanner
Copy link

In your example the ternary is evaluated before the call to current_user.follow

current_user.follow @user ? redirect_to root_url : redirect_to @user

Hopefully this will demonstrate part of the issue:

$ irb --simple-prompt
>> def foo(bar)
>>   puts bar
>>   bar == 'baz'
>> end                                                                                                                                                                                                                                        
=> nil
>> foo 'baz' ? 'left' : 'right'
(irb):10: warning: string literal in condition
left
=> false
>> foo('baz') ? 'left' : 'right'
baz
=> "left"

If you notice in the first call to foo (foo 'baz' ? 'left' : 'right'), the value of bar is not baz but left.

You will need to put parens all over the place for that ternary to work how you want:

current_user.follow(@user) ? redirect_to(root_url) : redirect_to(@user)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment