Reputation: 2869
How can I convert an ActiveRecord_AssociationRelation
into an array of Rails model instances?
I have code that is in an after_save
hook like this:
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
Is there a way to return an array of instances instead?
Table for reference:
create_table "likes", force: :cascade do |t|
t.integer "liker_id", null: false
t.integer "likee_id", null: false
...
end
I believe the problem is that Rails is not associating the models based on the foreign key of likee_id / liker_id.
Upvotes: 6
Views: 12006
Reputation: 81
Try ActiveRecord#to_a.
liker.likes.where(likee: liker).to_a
to_a()
publicConverts relation objects to Array.
Upvotes: 8