我正在从 Rails 教程中学习 Rails。我在11.3.1 节遇到了一个问题,代码清单 11.44 中的代码:
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
不会在 follow_user_ids 中返回 user_id。
在stackoverflow上搜索后,我在这里找到了解决方案,它说只需删除“join”方法就可以了。
但是我很好奇为什么在删除“加入”方法之前运行 RSPEC 时没有错误。
在清单 11.41 中:
subject { Micropost.from_users_followed_by(user) }
it { should include(own_post) }
it { should include(followed_post) }
如果“join”方法会使SQL语句出错,为什么RSPEC通过了?
有没有人有同样的问题?
更新 2012.04.03
我使用 Rails 控制台来检查问题。
user = User.first
ids = ids = user.following_users.map(&:id).join(', ')
哪个得到了
User Load (2.6ms) SELECT "users".* FROM "users" INNER JOIN "follows" ON
"follows"."followable_id" = "users"."id" AND "follows"."followable_type" = 'User' WHERE
"follows"."blocked" = 'f' AND "follows"."follower_id" = 1 AND "follows"."follower_type"
= 'User' AND "follows"."followable_type" = 'User'
=> "6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 55, 56, 5"
然后是 SQL
Collection.where("user_id IN (?)", ids)
结果是
Collection Load (0.7ms) SELECT "collections".* FROM "collections" WHERE (user_id IN
('6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 55, 56, 5')) ORDER BY collections.created_at DESC
=> []
返回一个空数组。
但我所有的 rspec 都通过了。还是不知道。