【问题标题】:first request to ActiveRecord boolean field with false value gives true in rails 3对具有 false 值的 ActiveRecord 布尔字段的第一个请求在 rails 3 中给出 true
【发布时间】:2011-05-17 12:42:01
【问题描述】:

我认为有这样的代码:

<% @items.each do |item| %>
<tr<%= raw(item.presence ? '' : ' class="opaque"') %>>
...
<td><%= item.presence ? 'Yes' : 'No' %></td>
</tr>
<% end %>

这是控制器中的请求:

@items = Item.where(:type_id => @type.id).order('brand ASC, name ASC').limit(limit).offset((@page-1)*limit)

'presence' 字段只是布尔值,第一项为 nil 尽管第一个获取的项目的存在字段为 nil,但它不会返回第一行的类 attr(就像它不是 nil 或 true),但第二个检查返回正确的值('No')。在具有 false 或 nil 值的其他行中,它在两次检查中都返回正确的值。这是一个错误,还是我做错了什么?

Rails 3.0.0,Postgres 8.4

【问题讨论】:

    标签: postgresql activerecord ruby-on-rails-3 actionview


    【解决方案1】:

    添加 ?到场帮助...

    <% @items.each do |item| %>
    <tr<%= raw(item.presence? ? '' : ' class="opaque"') %>>
    ...
    <td><%= item.presence? ? 'Yes' : 'No' %></td>
    </tr>
    <% end %>
    

    【讨论】:

    • 哦,谢谢。这真的很有帮助。但是我仍然对这种奇怪的行为感到气馁,同一个字段方法第一次给出错误的值,而在其余的时候给出正确的值。
    • 即使使用 ?强制 AR 将值视为布尔值,您在第一次调用中仍然没有得到 class="opauqe"?
    • 对不起,我错误地表达了自己。 ?您的答案中的方法始终有效。我不理解没有 ? 的方法的行为。
    • 我也不确定。没有 ? AR 只是将字段的值向上传递,然后三元 if 将其强制为布尔值。与? AR 正在转换为布尔值(因为不同的数据库有不同的方式来表示真假(即 tinyint(0) 或 tinyint(1)。't' || 'f' 等。)数据库或只是回显 item.presence 以查看 AR 正在使用的确切内容。
    • 实际上在 DB 中这个字段是 NULL,并且 item.presence.inspect 给出 nil
    猜你喜欢
    • 2013-11-09
    • 1970-01-01
    • 2011-08-26
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    相关资源
    最近更新 更多