I am learning rails from rails tutorial. I got a problem in the Section 11.3.1, the code in the Listing 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
will not return user_id in followed_user_ids.
After searching at stackoverflow, I found the solution here, which said that just remove the "join" method and it works for me.
But I am curious about why there is no error when I run RSPEC before remove the "join" method.
In Listing 11.41:
subject { Micropost.from_users_followed_by(user) }
it { should include(own_post) }
it { should include(followed_post) }
If the "join" method will make the SQL statement wrong, why RSPEC passed?
Does anyone have the same problem?
Update 2012.04.03
I used rails console to check the problem.
user = User.first
ids = ids = user.following_users.map(&:id).join(', ')
Which got
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"
Then the SQL
Collection.where("user_id IN (?)", ids)
The result is
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
=> []
Which return an empty array.
But I got all my rspec passed. Still no idea.
Assuming the join creates a string
'1,2,3', then perhaps you want tojoin("','")to have('1','2','3'), but I don’t think this will work – I’m sure PostgreSQL doesn’t like IDs as strings.Alternatively:
Squeel is a good SQL syntax gem where you could use:
This will allow you to pass in the array of integers and Squeel will setup the query where:
EDIT: You can also use the syntax: