How can I use a SQL “IN” statement with rails Active Record find and .map
-
23-08-2019 - |
Question
roles = Role.find_all_by_simulation_id(session[:sim_id])
forum_posts = Post.find(:all, :conditions => ["role_id = ? AND created_at > ?", roles.map(&:id), session[:last_login]])
Error:
SQLite3::SQLException: near ",": syntax error: SELECT * FROM "posts" WHERE (role_id = 1,2,3,4 AND created_at > '2009-05-21 11:54:52')
Solution
change this:
forum_posts = Post.find(:all, :conditions => ["role_id = ? AND created_at > ?", roles.map(&:id), session[:last_login]])
to
forum_posts = Post.find(:all, :conditions => ["role_id IN (?) AND created_at > ?", roles.map(&:id), session[:last_login]])
OTHER TIPS
I think the commas in Role_id = 1,2,3,4. I think it needs to be role_id='1,2,3,4' if its a string or role_id IN (1,2,3,4) if you want an OR style comparison on the integer.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow