Make searches using repetitions

1

I created the following method to search random people for a certain party, the problem is that if I want to add another ten people from another party it does not add, it only replaces the search with no party to such party

class Pessoa < ActiveRecord::Base
    class << self
        def filtra_pessoas()
            Pessoa.where(partido: "sem partido").order('rand()').first(10)
            #Pessoa.where(partido: "partido tal").order('rand()').first(10)
        end
    end
end
    
asked by anonymous 02.10.2016 / 16:48

1 answer

2
So Erasmo , this type of query will not accumulate because it is the normal behavior of any query : Search for new records. In other words, you will have to do this accumulation manually, let's try one of the possible approaches:

Again, the ideal thing is that you use scopes , your code gets cleaner, dry and in practice the usage is similar. Just exemplifying it would look like this:

class Pessoa < ActiveRecord::Base
    scope :filtra_pessoas, -> { where(partido: "sem partido").order('rand()').first(10) }
end

Now back to the question, to accumulate we need another method to do the dirty work:

TR; DR

class Pessoa < ActiveRecord::Base
  scope :filtra_pessoas, -> { where(partido: "sem partido").order('rand()').first(10) }
  @pessoas_aleatorias = []

  def self.acumula
    @pessoas_aleatorias += filtra_pessoas
  end

end

Re-emphasizing that you will have the problem of repeated registrations that will give a certain headache to solve. You can use uniq to solve this, but you will not be able to have the closed amount 10, 20, 30 ... always, ie the solution to this will depend a lot on your model business.

    
04.10.2016 / 13:57