Philip7899
Philip7899

Reputation: 4677

Rails - .where method not working

I have the following code in my top navigation menu:

<% if current_user.relationships.where(state: 'active') %>
    <li><%= link_to 'New Schedule', new_schedule_path %></li>
<% end %>

Users have_many relationships. 'state' is a column in the relationships table. I only want the link to appear if the user has a relationship where the value of the state column is set to 'active'. For some reason, This link is appearing to user's who do not have relationship with state = active. How do I fix this?

Upvotes: 0

Views: 281

Answers (2)

Rebitzele
Rebitzele

Reputation: 3282

Use:

current_user.relationships.where(state: 'active').any?

Since even if there are no relationships, the where method will still return an empty array, which is not nil.

Upvotes: 0

Santhosh
Santhosh

Reputation: 29094

You should change it to

current_user.relationships.where(state: 'active').exists?

or

current_user.relationships.where(state: 'active').first

current_user.relationships.where(state: 'active') will return an ActiveRelation object, and it is not evaluated to false in Ruby. Only nil of false is

Upvotes: 2

Related Questions