将记录合并到ActiveRecord关系中 [英] Merge record into ActiveRecord Relation

查看:92
本文介绍了将记录合并到ActiveRecord关系中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我提取一条记录为:

def self.imp_broadcast_preview!
  Broadcast.where(for_gamers: true).order(:created_at).last
end

然后在我的控制器中有:

And then in my controller I have:

def index
  @conversations = Conversation.where(gamer: @gamer)
  @conversations << Broadcast.imp_broadcast_preview!
end

上面的代码在Rails 4.2中正常工作,并合并了对话中的最后一条广播消息.我刚刚将代码库更新为Rails 5.2,现在出现错误:

The above code works properly in Rails 4.2 and merges the last broadcast message in the conversations. I just updated my codebase to Rails 5.2 and now I am getting an error:

NoMethodError (undefined method `<<' for #<Conversation::ActiveRecord_Relation:0x00007fd2541baca0>)

我尝试改用merge,但由于broadcast不是activerecord relation

I tried using merge instead but that throws an error as well since broadcast is not an activerecord relation

推荐答案

该功能已在Rails 5.0中删除,您可以检查 https://github.com/rails/rails/issues/25906 .在那里,您将找到为什么删除了它,以及指向删除了该功能的提交的链接.

That functionality got removed in rails 5.0, you can check https://github.com/rails/rails/issues/25906. There you'll find why it was removed, and the link to the commit that removed that functionality.

要使代码正常工作,您应该做的就是将第一个结果转换为数组,这样<<就会起作用:

To make your code work, what you should do is to convert to an Array your first result, that way << will work:

def index
  @conversations = Conversation.where(gamer: @gamer).to_a
  @conversations << Broadcast.imp_broadcast_preview!
end

这篇关于将记录合并到ActiveRecord关系中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆