【问题标题】:Ruby on Rails Hash#slice method returns empty hashRuby on Rails Hash#slice 方法返回空哈希
【发布时间】:2015-05-28 20:31:01
【问题描述】:

为什么第一个例子返回一个带有两个指定键的散列,而第二个例子返回一个散列?

User.last.slice(:created_at, :updated_at)
=> {"created_at"=>Fri, 22 May 2015 00:33:37 UTC +00:00, "updated_at"=>Fri, 22 May 2015 01:00:06 UTC +00:00}

User.last.attributes.slice(:created_at, :updated_at)
=> {}

请注意示例中的不同之处在于使用了.attributes,它返回Hash

User.last.attributes.class
=> Hash

【问题讨论】:

    标签: ruby-on-rails-4 hash slice ruby-2.0 activesupport


    【解决方案1】:

    我刚刚尝试了一些东西(属性键是字符串而不是符号)

    User.last.attributes.slice("created_at", "updated_at")
    

    【讨论】:

    • 你说得对!我找到了解决方案,如果没有人回答,我会自己写。我已经习惯了使用 HashWithIndifferentAccess 代替哈希的 Rails。
    猜你喜欢
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 2014-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多