0

I want to merge two relationships in the user model to one relationship

I have the following database setup:

class User < ActiveRecord::Base
  has_many :shared_cards
  has_many :card_instances
  has_many :shared_card_instances, through: :shared_cards, source: :card_instances
end

class CardInstance < ActiveRecord::Base
  belongs_to :user
  belongs_to :shared_card
end

class SharedCard < ActiveRecord::Base
  belongs_to :user
  has_many :card_instances
end

I want to merge 'card_instances' and 'shared_card_instances' in the users table to example 'all_card_instances'

The reason I want to merge them is because I want to get an ActiveRecord::Relation out so I can search and sort directly on all objects

Edit:

My current way of doing it:

all_card_instances = CardInstance.find_by_id(user.card_instances.pluck(:id) | user.shared_card_instances.pluck(:id))

And now I can call '.order' and my pg_search_scope's directly on the returned ActiveRecord::Relation object

But this way I believe it does unnecessary queries to first grab all objects from the two sources and then grab them all again in the merged query.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jonas
  • 147
  • 3
  • 11
  • 3
    not quite sure on what you mean by "merge", do you mean put all the attributes on one flat long row and scrap both instances? – YaBoyQuy Aug 27 '12 at 23:48
  • See my edit, i might give you more info of what i'm trying to do. – Jonas Aug 28 '12 at 08:41
  • It should be like this, but instead of AND it should be OR between the relationships. http://stackoverflow.com/questions/9540801/combine-two-activerecordrelation-objects – Jonas Aug 28 '12 at 10:39

0 Answers0