Merge record into ActiveRecord Relation

╄→尐↘猪︶ㄣ 提交于 2020-01-25 06:34:05

问题


I pull a record as:

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

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>)

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


回答1:


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


来源:https://stackoverflow.com/questions/53891347/merge-record-into-activerecord-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!