gpt4 book ai didi

ruby-on-rails - 如何将 ActiveRecord_AssociationRelation 转换为 ActiveRecord 中的数组?

转载 作者:行者123 更新时间:2023-12-03 21:29:47 24 4
gpt4 key购买 nike

如何转换 ActiveRecord_AssociationRelation到 Rails 模型实例数组中?

我有 after_save 中的代码像这样的钩子(Hook):

class Like < ApplicationRecord
belongs_to :likee, class_name: 'User', foreign_key: 'likee_id'
belongs_to :liker, class_name: 'User', foreign_key: 'liker_id'

after_save :mutual_like?

private

def mutual_like?
if liker.likes.where(likee: liker) // returns collection proxy but I want to return an array of model instances so that I can create another model

end
end
end

有没有办法返回一个实例数组呢?

供引用的表格:
  create_table "likes", force: :cascade do |t|
t.integer "liker_id", null: false
t.integer "likee_id", null: false
...
end

我认为问题在于 Rails 没有根据 likee_id/liker_id 的外键关联模型。

最佳答案

试试 ActiveRecord#to_a .liker.likes.where(likee: liker).to_a

to_a() public

Converts relation objects to Array.

关于ruby-on-rails - 如何将 ActiveRecord_AssociationRelation 转换为 ActiveRecord 中的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39824558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com