3

What's the best way to dynamically remove a model from a query? Basically I want to find all campaigns where a user hasn't already provided a response.

The below method delete_at actually deletes the model which isn't what I want. I only want it remove from the local 'campaigns' ActiveRecord::Relation query set that I got.

def self.appuser_campaigns appuser_id, language
        appuser = Appuser.find(appuser_id)

        campaigns = Campaign.check_language language
        i = -1
        campaigns.each do |campaign|
            i = i + 1
            responses = Response.where(appuser_id: appuser_id, campaign_id: campaign.id)
            if responses.length > 0
                campaigns.delete_at(i)
            end
        end
        puts campaigns.class.name #"ActiveRecord::Relation" 

        campaigns
    end

    def self.check_language language
        campaigns = Campaign.where(language: language, status: "In Progress")
    end
Tom Hammond
  • 5,842
  • 12
  • 52
  • 95
  • Can you post your models with relations please. You want it where a specific user hasn't responded right? – j-dexx Dec 07 '15 at 15:55
  • My previous answer will help you: http://stackoverflow.com/questions/18082096/rails-4-scope-to-find-parents-with-no-children/18082147#18082147 – MrYoshiji Dec 07 '15 at 16:04

1 Answers1

1

You can do the following:

already_answered_campaign_ids = Appuser.find(appuser_id).responses.pluck(:campaign_id)
Campaign.where('id NOT IN (?)', already_answered_campaign_ids.presence || -1)
MrYoshiji
  • 54,334
  • 13
  • 124
  • 117