RailsTutorial 3.2 Ch 11 - PostgreSQL syntax error breaks the status feed

拟墨画扇 提交于 2019-12-22 14:03:38

问题


I'm in Section 11.3.1 of the Rails Tutorial, and all tests were passing prior to this. Afterward, the home page (which has the micropost feed) breaks with this error:

PG::Error: ERROR:  invalid input syntax for integer: "98, 1"
LINE 1: ...CT COUNT(*) FROM "microposts"  WHERE (user_id IN ('98, 1') O...
                                                             ^
: SELECT COUNT(*) FROM "microposts"  WHERE (user_id IN ('98, 1') OR user_id = 101)

And several of the tests fail with a similar issue. Here's the first one:

1) Authentication authorization as wrong user visiting Users#edit page 
   Failure/Error: before { visit edit_user_path(wrong_user) }
   ActionView::Template::Error:
   PG::Error: ERROR:  invalid input syntax for integer: ""
   LINE 1: ...CT COUNT(*) FROM "microposts"  WHERE (user_id IN ('') OR use...
                                                                ^

Now, I am using PostgreSQL instead of the default SQLite3, so it may be that there is a syntax conflict, but I'm not positive. I'm not super familiar with Postgres (just using it to make the Heroku deploy cleaner).

It looks like the home page error is coming from the ids being passed to the query with quotes - I went into psql to test a few queries and this is successful:

SELECT "microposts".* FROM "microposts" WHERE "microposts"."id" IN (1,2,3);

while this fails:

SELECT "microposts".* FROM "microposts" WHERE "microposts"."id" IN ('1,2,3');

And the spec error is coming from an empty array being passed, equivalent to this, which also fails:

SELECT "microposts".* FROM "microposts" WHERE "microposts"."id" IN ('');

Can anyone who is familiar with PostgreSQL syntax tell me how to rewrite the method definition to fix this issue?

The current method in micropost.rb looks like this:

def self.from_users_followed_by(user)
    followed_user_ids = user.followed_user_ids.join(', ')
    where("user_id IN (?) OR user_id = ?", followed_user_ids, user)
end

And the call from `users.rb' looks like this:

def feed
    Micropost.from_users_followed_by(self)
end

回答1:


Holy crap, I actually figured this out myself. Just had to remove the join in the method definition:

def self.from_users_followed_by(user)
    followed_user_ids = user.followed_user_ids
    where("user_id IN (?) OR user_id = ?", followed_user_ids, user)
end

user.followed_user_ids.join(', ') produces this: "1, 2, 3"

while

user.followed_user_ids produces this: 1, 2, 3

which is what I wanted.



来源:https://stackoverflow.com/questions/9397954/railstutorial-3-2-ch-11-postgresql-syntax-error-breaks-the-status-feed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!