2013-07-19 67 views
0

此方法从数据库返回一些记录。在rails上添加红宝石查询

def wall_record(ref_id,followers_record,pid,sd_pid) 
     @Wp_rec=Wallpost.select('Wp.id as Pid,Wp.*,Wi.id as Iid,Wi.imagename,Wv.videourl,U.firstname,U.username') 
     @[email protected]_rec.where('Wp.id > ? ', pid) if pid.present? # pid->PostId 
     @[email protected]_rec.where('Wp.id < ? ', sd_pid) if sd_pid.present? # sd_pid -> Scroll down 
     @[email protected]_rec.where('Wp.posted_by IN (?) ', followers_record) if followers_record.present? 
     @[email protected]_rec.joins('Wp INNER JOIN `epoker_wallimages` as Wi on Wi.wallpost_id = Wp.id') 
     @[email protected]_rec.joins('INNER JOIN `epoker_users` as U on U.id = Wp.user_id') 
     @[email protected]_rec.joins('INNER JOIN `epoker_wallvideos` as Wv on Wv.wallpost_id = Wp.id') 
     @[email protected]_rec.order('Wp.id DESC') if followers_record.present? 
     @[email protected]_rec.limit(5) #if followers_record.present? 
     end 

现在我想添加MySQL查询 - >where((Wp.posted_by != 100000 AND post_status = 1) OR (Wp.posted_by = 10000 AND post_status in (1,2)))

我怎么能做到这一点吗?

回答

1

这是很容易=)

只包括条件你想要什么到报价:

where("(Wp.posted_by != 100000 AND post_status = 1) OR (Wp.posted_by = 10000 AND post_status in (1,2))") 

,你甚至可以通过引号内的任何PARAM你想

where("(Wp.posted_by != 100000 AND post_status = #{post_status}) OR (Wp.posted_by = #{posted_by} AND post_status in (#{post_statuses_array.join(',')}))") 

最后,你可以使用更多的轨道式方法

where("(Wp.posted_by ? != AND post_status = ?) OR (Wp.posted_by = ? AND post_status in (?))",100000, 1, 10000, [1,2]) 

而不是Wp模型,你必须通过真正的表名!(但据我可以看到它是你的表名..不是很方便,顺便说一下)

+0

谢谢@okliv它的工作。 – Gagan

+1

第二种方法可能使您容易受到SQL注入的攻击,第三种方法更受欢迎,除非您可以绝对确定用户无法将任意数据放入查询。 – Slicedpan