Post.where() causing 500 error

(Andrew Byrne) #1

Noooob question (2 days ruby experience :wink:
I have a plugin almost doing what I want but have a hang up here:

 posts = Post.where('user_id = ? and post_number = ?', params["uid"], params["tid"])
		      .order(created_at: :desc)

I’ve tried a number of versions. but they all case errors .
It feels more like a query issues than syntax but I bow before the experts edu-mecate me.

(Alan Tan) #2

What does the logs say? :slight_smile:

(Andrew Byrne) #3

so good of you to ask, and admittedly that helped… :smiley:

BUT perhaps you can assist further with my query! The issue was the input value
while I can do

Post.where('user_id: '1,2') #works

Post.where('topic_id: '4,5')  #works

Post.where('user_id = ? or topic_id = ?', '1,2', '4, 5') #fails!

So again I assume! I’ll need to iterate over each user id, but… NOOOOB (assistance greatly appreciated!

(Alan Tan) #4

So why did it fail? What is the error that was raised when you ran the code? :slight_smile:

(Andrew Byrne) #5

Boom! (thanks BTW )

ActiveRecord::StatementInvalid (PG::InvalidTextRepresentation: ERROR:  invalid input syntax for integer: "1,2"
LINE 1: ...ERE ("posts"."deleted_at" IS NULL) AND (user_id = '1,2' or t...
: SELECT  "posts".* FROM "posts" WHERE ("posts"."deleted_at" IS NULL) AND (user_id = '1,2' or topic_id = '4')  ORDER BY "posts"."created_at" DESC LIMIT 30)
/var/lib/gems/2.2.0/gems/rack-mini-profiler- `exec'

(Alan Tan) #6

Try Post.where(user_id IN (?) OR topic_id IN (?), [1,2], [4,5])


So if I say post.where() it causes a error?

(Andrew Byrne) #8

@tgxworld Thanks that helped a bunch.

For the record I was doing a bunch of stuff that I SHOULD have known better…

  1. not splitting the string to an actual array (duh facepalm )
  2. your request seems to have fix the syntax issues (woot)

final code

uid = params["uid"].split(",")
tid =  params["tid"].split(",")

posts = Post.where('user_id IN (?) OR topic_id IN (?)', uid, tid )
			.order(created_at: :desc)

obj = {follow_posts: posts }
render json: obj

Massive thanks!! :smiley:

(Kane York) #9

This topic was automatically closed after 2 days. New replies are no longer allowed.