简体   繁体   中英

Append query in ruby on rails

This method returned some record from database.

   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')
        @Wp_rec=@Wp_rec.where('Wp.id > ? ', pid) if pid.present? # pid->PostId
        @Wp_rec=@Wp_rec.where('Wp.id < ? ', sd_pid) if sd_pid.present? # sd_pid -> Scroll down
        @Wp_rec=@Wp_rec.where('Wp.posted_by IN (?) ', followers_record)  if followers_record.present?
        @Wp_rec=@Wp_rec.joins('Wp INNER JOIN `epoker_wallimages` as Wi on Wi.wallpost_id = Wp.id')
        @Wp_rec=@Wp_rec.joins('INNER JOIN `epoker_users` as U on U.id = Wp.user_id')
        @Wp_rec=@Wp_rec.joins('INNER JOIN `epoker_wallvideos` as Wv on Wv.wallpost_id = Wp.id')
        @Wp_rec=@Wp_rec.order('Wp.id DESC') if followers_record.present?
        @Wp_rec=@Wp_rec.limit(5) #if followers_record.present?
      end

Now i want to add mysql query -> where((Wp.posted_by != 100000 AND post_status = 1) OR (Wp.posted_by = 10000 AND post_status in (1,2)))

How can I do this please?

it is very easy =)

just include condition what you want into quotes:

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

you can even pass inside quotes any param you want

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

and finally, you can make it with more rails-like approach

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

instead of Wp model you have to pass real table name! (but as far as i can see it is your table name.. not very convenient, by the way)

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