简体   繁体   中英

Rails - Searchlogic to search condition as an array of value

I have two models Employee & Unit . Unit has many Employees . I am using SearchLogic to search employee model. What is the equivalent of below SQL in Searchlogic

employees.unit_id IN (1,2,3)

I have tried both

unit_id_equals_all[] 
unit_id_equals_any[]

But nothing works. Can anyone help?

Thanks, Abhilash

Employee.unit_id_equals([1, 2, 3])

Same problem here.

I have no idea why this worked for me, or why I even tried it, since it is undocumented. But I changed the _equals to _in, and it produced the SQL with IN, and worked perfectly.

Employee.unit_id_in([1, 2, 3])

We had this same issue with a Rails 2.3.12 project. With searchlogic 2.4.7 we could do:

User.id_equals([1,2,3])

After upgrading to search logic 2.5.8 (deprecation messages in the old one were cluttering out cucumber and spec output), this syntax no longer worked. It threw this error just like the one above:

ActiveRecord::StatementInvalid: Mysql::Error: Operand should contain 1 column(s): SELECT * FROM `users` WHERE (users.id = 1, 2, 3) 

After trying the solutions above, we found that these two syntax alternatives worked:

User.id_in([1,2,3]) <-- as suggested above
User.id_equals_any([1,2,3])

In other words, without the "_any" the new search logic produces invalid mysql. Looking into when and why this change might have occurred, I found this commit discussion:

Github commit changing handling of arrays

The upshot of this change and the discussion was to require _any for times when you want a match against any value in the array, and otherwise just pass the array in to the equals statement directly without changing the SQL to "IN" as needed for multiple values.

Reverting to 2.4.7 clears the error. Changing all the calls to the more explicit _any or _in is what we ended up doing in order to avoid deprecation errors. Hope this helps and adds to the very helpful answers above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM