Question

Here's my code:

- unless Relationship.are_friends?(current_user, @user) && (current_user != @user)
  - puts "d"*100
  - puts "#{current_user.inspect}"
  - puts "#{@user.inspect}"
  = link_to "Add Friend", controller: "relationships", action: "req", name: @user.name,      remote: true, class: "friend_link"

Basically the second condition "current_user != @user" is not working and I don't know why. When I puts the current user and @user they are working correctly. @user = User.find_by_name(params[:name]).

Thanks for the help!

Was it helpful?

Solution

I assume this is your requirement. Allow A to add B as a friend if:

  • A and B are not already friends AND
  • A and B are not the same person

So, in pseudo-code, unless (already_friends or same_person) allow_add_friend end

If this is your requirement, your statement should read:

unless Relationship.are_friends?(current_user, @user) or (current_user == @user)

Note that && changed to or and != changed to ==.

OTHER TIPS

unless is often a bit counterintuitive, especially with multiple conditions. Look at it this way:

true && false # => false, code is executed
false && true # => false, code is executed

The only condition in which the block is skipped is:

true && true  # => true, code is not executed

I imagine what you're trying to do is skip the block is either condition is true, in which case you need to use the || operator:

unless Relationship.are_friends?(current_user, @user) || (current_user == @user)
  #etc..
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top