问题描述
我在 第 11.3.1 节Rails 教程,并且在此之前所有测试都通过了.之后,主页(包含微博提要)因以下错误而中断:
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...
^
现在,我使用的是 PostgreSQL 而不是默认的 SQLite3,所以可能存在语法冲突,但我并不肯定.我对 Postgres 不是很熟悉(只是用它来使 Heroku 部署更干净).
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).
看起来主页错误来自使用引号传递给查询的 id - 我进入 psql 来测试一些查询,这是成功的:
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);
虽然失败了:
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 ('');
熟悉 PostgreSQL 语法的人能告诉我如何重写方法定义来解决这个问题吗?
micropost.rb
中的当前方法如下所示:
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
来自`users.rb'的调用看起来像这样:
And the call from `users.rb' looks like this:
def feed
Micropost.from_users_followed_by(self)
end
推荐答案
天哪,我自己真的想通了.只需删除方法定义中的连接:
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(', ')
产生这个:"1, 2, 3"
user.followed_user_ids.join(', ')
produces this: "1, 2, 3"
同时
user.followed_user_ids
产生这个:1, 2, 3
user.followed_user_ids
produces this: 1, 2, 3
这正是我想要的.
这篇关于RailsTutorial 3.2 Ch 11 - PostgreSQL 语法错误破坏了状态提要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!