searchlogic
searchlogic copied to clipboard
Multiple record copies returned for habtm association
I committed a test case that reproduces the problem in http://github.com/infrared/searchlogic/commit/34d3b89122812df2b4fa9a0c8339674ecf25f206
When you have two models joined with has_and_belongs_to_many and you search one of them with something like:
FirstModel.search(:second_models_id_equals_any => [1, 2]).all
multiple copies of the same FirstModel record will be returned if a the record happens to be associated with more than one SecondModels.
Same issue here. Definitely not the expected behavior.
I have the same issue, using a plain has_many association.
I've been fighting this issue for a while... is there a work around?
I've worked around this by writing a custom named scope. Using my original example, I could write something like this:
class FirstModel
named_scope :with_second_models, lambda {|ids|
matches = ids.map{ "second_model_id = ?" }.join(" OR ")
{:conditions => "first_models.id IN (SELECT first_model_id FROM the_join_table WHERE #{matches})"}
}
end
After that it can be used like this:
FirstModel.search(:with_second_models => [1, 2]).all
Should be {:conditions => ["first_models.id IN (SELECT first_model_id FROM the_join_table WHERE #{matches})", *ids]}
the resulting SQL was ... WHERE secon_model_id = ? OR second_model_id = ?))
will be ... WHERE secon_model_id = 1 OR second_model_id = 2))