searchlogic icon indicating copy to clipboard operation
searchlogic copied to clipboard

Multiple record copies returned for habtm association

Open mkwiatkowski opened this issue 16 years ago • 5 comments
trafficstars

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.

mkwiatkowski avatar Oct 03 '09 07:10 mkwiatkowski

Same issue here. Definitely not the expected behavior.

laserlemon avatar Dec 08 '09 17:12 laserlemon

I have the same issue, using a plain has_many association.

peterjm avatar Jan 07 '10 03:01 peterjm

I've been fighting this issue for a while... is there a work around?

swr avatar Feb 27 '10 01:02 swr

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

mkwiatkowski avatar Feb 27 '10 08:02 mkwiatkowski

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))

vsalbaba avatar Mar 03 '11 10:03 vsalbaba