I’m trying to select a random record, but the only working method seems like a horrible performance liability.
First attempt, using RANDOM function from Postgres – throws “Can’t convert Hash into Integer”
assigned_specialist = User.specialists.legal_for(coach_section).experienced_in(critique.discipline_id).first(:order => "RANDOM()")
return assigned_specialist.id
Second attempt, using offset method discussed here. Also causes “Can’t convert Hash into Integer”
legal_specialists = User.specialists.legal_for(coach_section).experienced_in(critique.discipline_id)
offset = rand(legal_specialists.count)
assigned_specialist = legal_specialists.first(:offset => offset)
return assigned_specialist.id
Final attempt, using array sample method, which works but seems bad.
legal_specialists = User.specialists.legal_for(coach_section).experienced_in(critique.discipline_id)
assigned_specialist = legal_specialists.sample
return assigned_specialist.id
To be fair, there will only be about 20 specialists in the system, so the array sample method might never cause any issues, but I’d still like to understand what’s going on here.
Edit: Here are the scopes I defined:
scope :specialists, where(:role_id => 2)
scope :legal_for, lambda { |coach_section| where("section_id != ?", coach_section) }
scope :experienced_in, lambda { |discipline_id|
discipline = Discipline.find(discipline_id)
discipline.users
}
What about :
It does query all the table, so you just have a shorter version … wonder if there’s a better way to do it!
Edit : Did you try this? It’s supposed to work :
Take a look at the thread here : Rails 3: Get Random Record. It shows different ways to do it
Also look at this gem : https://github.com/spilliton/randumb
Seems to implement what you want to do, in a clean way
Edit : replace with this ?
This way your scope will give you back an
ActiveRecord::Relationobject. I assumed theUsermodelhas_many :habtm_modelsso replace with the real name!