如何在rails Active Record find和.map中使用SQL“IN”语句

时间:2022-02-26 22:44:53
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') 

2 个解决方案

#1


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

#2


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.

我认为Role_id中的逗号= 1,2,3,4。如果你想在整数上进行OR样式比较,我认为它必须是role_id ='1,2,3,4',如果它是一个字符串或role_id IN(1,2,3,4)。

#1


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

#2


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.

我认为Role_id中的逗号= 1,2,3,4。如果你想在整数上进行OR样式比较,我认为它必须是role_id ='1,2,3,4',如果它是一个字符串或role_id IN(1,2,3,4)。