vendredi 23 février 2018

Returning an ActiveRecord Object from two different Tables

I am trying to return an ActiveRecord object consisting of two different objects from two different tables. They have the following relations:

class User < ApplicationRecord
  has_many :posts, dependent: :destroy
  has_many :pictures, dependent: :destroy

  # Ideally user.timeline returns all of a user's posts and pictures as an active record relation.

  def timeline
      Post.where("(user_id = :user_id)", user_id: id)
      Picture.where("(user_id = :user_id)", user_id: id)    
  end
end

class Post < ApplicationRecord
  belongs_to :user
end

class Picture < ApplicationRecord
  belongs_to :user
end

I would like to be able to call user.timeline and have all of a user's posts and pictures returned together as one active record relation.

I have tried: Post.where("(user_id = :user_id)", user_id: id) + Picture.where("(user_id = :user_id)", user_id: id). This returns all the objects I want, but as an array, not an active record relation.

Is there any way this can be done?

Aucun commentaire:

Enregistrer un commentaire