How do I generate an ActiveRecord Relation and make sure to include specific objects within the collection?

61 views Asked by At

I want to generate an ActiveRecord relation that looks like this:

@profiles = Profile.published.order("RANDOM()").limit(8) + Profile.where(demo_linked: true)

The issue with the above is that it returns an array, which is what I don't want.

I would like the above to be an ActiveRecord relation.

Thoughts?

2

There are 2 answers

0
marcamillion On BEST ANSWER

I eventually got it with the following:

    @selected_profile = Profile.published.where(demo_linked: true)
    @random_profiles = Profile.published.order("RANDOM()").limit(8).where.not(id: @selected_profile.pluck(:id))
    @profiles = @random_profiles + @selected_profile
1
Tim Lawrenz On

As described in the guides:

random_published_profiles = Profile.published.order("RANDOM()").limit(8)
demo_linked_profiles = Profile.where(demo_linked: true)

all_profiles = random_published_profiles.merge(demo_linked_profiles)