如何将ActiveRecord_AssociationRelation转换为ActiveRecord中的数组?

时间:2016-10-03 04:17:11

标签: ruby-on-rails

如何将ActiveRecord_AssociationRelation转换为Rails模型实例数组?

我的代码位于after_save钩子中,如下所示:

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的外键关联模型。

1 个答案:

答案 0 :(得分:3)

尝试ActiveRecord#to_a

liker.likes.where(likee: liker).to_a

  

to_a() public

     

将关系对象转换为Array。