Post.where() causing 500 error

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)
		      .limit(params["total"])

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.

What does the logs say? :slight_smile:

1 Like

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

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

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

Fails
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!

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

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-0.9.9.2/lib/patches/db/pg.rb:93:in `exec'

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

2 Likes

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

@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)
			.limit(params["total"])
			.offset(params["start"])

obj = {follow_posts: posts }
render json: obj

Massive thanks!! :smiley:

5 Likes

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