【问题标题】:Rails - .where method not workingRails - .where 方法不起作用
【发布时间】:2013-11-20 17:42:39
【问题描述】:

我的顶部导航菜单中有以下代码:

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

用户有_many 关系。 “状态”是关系表中的一列。我只希望在用户具有状态列的值设置为“活动”的关系时显示链接。出于某种原因,此链接出现给与 state = active 没有关系的用户。我该如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails ruby model-view-controller ruby-on-rails-4 where-clause


    【解决方案1】:

    你应该把它改成

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

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

    current_user.relationships.where(state: 'active') 将返回一个 ActiveRelation 对象,并且在 Ruby 中它不会被评估为 false。只有nil 中的false

    【讨论】:

    • @Philip7899 不,它只是返回一个 ActiveRelation 对象。在对象上调用exists?firsteach 之前,不会发生SQL 查询,延迟加载!! :)
    【解决方案2】:

    用途:

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

    由于即使没有关系,where方法仍然会返回一个空数组,不是nil。

    【讨论】:

      猜你喜欢
      • 2017-08-03
      • 2016-04-17
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-12
      • 2020-02-22
      • 2016-12-26
      相关资源
      最近更新 更多