5

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.

user3162553
  • 2,699
  • 3
  • 37
  • 61

1 Answers1

7

Try ActiveRecord#to_a.

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

to_a() public

Converts relation objects to Array.

Community
  • 1
  • 1
leland
  • 71
  • 2
  • 1
    I tried that and I get `ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column likes.user_id does not exist` – user3162553 Oct 03 '16 at 05:09
  • You need a [migration](http://edgeguides.rubyonrails.org/active_record_migrations.html) that adds the database columns for `liker_id` and `likee_id`. Related answer: http://stackoverflow.com/questions/22815009/add-a-reference-column-migration-in-rails-4 – leland Oct 03 '16 at 05:19
  • Seems like your problem in in the definition of the association `has_many :likes` in the `User` class. You need to specify the foreign_key there too. – Diego Nolde Jan 04 '21 at 11:08