简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM