Created
April 20, 2012 00:20
-
-
Save krisf/2424980 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
#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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In your example the ternary is evaluated before the call to
current_user.follow
Hopefully this will demonstrate part of the issue:
If you notice in the first call to
foo
(foo 'baz' ? 'left' : 'right'
), the value ofbar
is notbaz
butleft
.You will need to put parens all over the place for that ternary to work how you want: