Ank Ag wrote:
I get the relation_ids to be searched in an array from the user. The
user wants to find all the people who has all the relation_ids he has
specified.
Can anyone solve this Query.
I’m sure, depending on your database, there are various ways of writing
queries using sub-queries, etc which will enable you to use
find_by_sql() to do what you want and they will all be incomprehensible
the next day (I expect).
Not ideal, but if the user is providing the list can I assume that it is
unlikely to be tooooo big? If this is the case, then you are best
starting with relations as otherwise you must scan all people in case
they have that relation. So, if the array from the user is users_array
and these will be IDs from the relation table, then:
people_arrays = []
users_array.each do |n|
people_arrays << Relation.find(n).people
end
This gives people_arrays as an array of arrays of people. Now the
problem is which people are in each sub-array which is just the
intersection of arrays.
Less efficient than doing everything in one big SQL perhaps, but much
more readable and maintainable.
Alternatively, get all the relations in one go:
relation_array = Relation.find(:all, :conditions => “relations.id in
(#{users_array.join ‘,’})”, :include => :people) unless
users_array.blank?
Now you have everything in memory that you need. This time, you need to
find the intersection of the arrays:
relation_array[n].people
Either way, you reduce the problem of finding the intersection from the
database to one of finding the intersection of an array of arrays which
is much easier.