Perform searches using repetitions

Asked

Viewed 54 times

1

I created the following method to fetch random people from a certain party, the problem is that if I want to add ten more people from another party it does not add, only replaces the search without party for 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
  • It even rolls do, but you will have a problem with repeated records. This is a problem for you?

  • Repeating the records is a problem yes, but the way it is at the moment does not repeat. believes that it will not repeat, because the same party is not sought more than once

  • The way you are not going to repeat because you are only looking for the first 10, I say there is a solution to accumulate another 10 elements, but this will cause problems with duplication.

  • I understand, show me how it can be done and then I try something different, at first I want to understand why the query replaces the first search by the second instead of accumulating. I don’t know if you understand =D I’m new to Ruby on Rails

1 answer

2


So Erasmus, this type of consultation will not accumulate, as it is the normal behavior of any query: Search for new records. That is you will have to do this accumulation manually, let’s try one of the possible approaches:

Again the ideal in this case is that you use scopes, your code gets cleaner, dry and in practice the use is similar. Only exemplifying would be 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

Pointing out again that you will get the problem of repeated records that will give a certain headache to solve. You can use the uniq to solve this, but you will not be able to have the quantity closed 10, 20, 30... always, ie the solution to this will depend a lot on your business model.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.