【问题标题】:Rails 4.1 ActiveRecord::relation is no more like ArrayRails 4.1 ActiveRecord::relation 不再像 Array
【发布时间】:2014-05-23 07:34:27
【问题描述】:

在 Rails 4.0.4 中,此代码有效:

mailboxes = Mailbox.order(:mailbox)
mailboxes.keep_if do |mailbox|
  # test
end

在 Rails 4.1.0 中,它与 NoMethodError (undefined method keep_if for <Mailbox::ActiveRecord_Relation:0x5494f80>) 中断

必须改成

mailboxes = Mailbox.order(:mailbox).to_a
mailboxes.keep_if do |mailbox|
  # test
end

我没有找到任何相关信息

有什么想法吗?

【问题讨论】:

    标签: ruby activerecord ruby-on-rails-4


    【解决方案1】:

    它在 release notes 中用于 rails 4.1

    Relation 不再有 #map 之类的 mutator 方法!和#delete_if。 在使用这些方法之前调用#to_a 转换为数组。 (拉 请求)

    由于keep_if 是一个mutator 方法,它从Relation 中删除

    【讨论】:

    • 这解释了为什么我无法在“respond_with User.all”上获得正确的 JSON 响应。但是做一个 respond_with User.all.to_a 正确地调用了我的 to_json 方法,并给了我想要的结果。谢谢!
    • Modal.order 调用后解决了我的错误:NoMethodError (undefined method 'sort_by!' for #<Modal::ActiveRecord_Relation>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多