Skip to content

Instantly share code, notes, and snippets.

@synth
Last active August 29, 2015 14:01
Show Gist options
  • Save synth/3f7f4e4726b8e3db2539 to your computer and use it in GitHub Desktop.
Save synth/3f7f4e4726b8e3db2539 to your computer and use it in GitHub Desktop.
rails 4.1.0 bug when finding multiple records while joining a has_many association
rails g model Post
rails g model Comment post_id:integer comment:string
rails c
p1 = Post.create
p2 = Post.create
p1.comments.create(comment: "1")
p1.comments.create(comment: "2")
p2.comments.create(comment: "3")
p2.comments.create(comment: "4")
p2.comments.create(comment: "5")
2.1.1 :001 > Post.pluck(:id)
(0.4ms) SELECT "posts"."id" FROM "posts"
=> [1, 2]
2.1.1 :002 > Comment.all
Comment Load (0.6ms) SELECT "comments".* FROM "comments"
=> #<ActiveRecord::Relation [#<Comment id: 1, post_id: 1, comment: "1", created_at: "2014-05-06 22:22:19", updated_at: "2014-05-06 22:22:19">, #<Comment id: 2, post_id: 1, comment: "2", created_at: "2014-05-06 22:22:24", updated_at: "2014-05-06 22:22:24">, #<Comment id: 3, post_id: 2, comment: "3", created_at: "2014-05-06 22:22:46", updated_at: "2014-05-06 22:22:46">, #<Comment id: 4, post_id: 2, comment: "4", created_at: "2014-05-06 22:22:49", updated_at: "2014-05-06 22:22:49">, #<Comment id: 5, post_id: 2, comment: "5", created_at: "2014-05-06 22:22:51", updated_at: "2014-05-06 22:22:51">]>
2.1.1 :003 > Post.first.comments
Post Load (0.1ms) SELECT "posts".* FROM "posts" ORDER BY "posts"."id" ASC LIMIT 1
Comment Load (0.1ms) SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = ? [["post_id", 1]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Comment id: 1, post_id: 1, comment: "1", created_at: "2014-05-06 22:22:19", updated_at: "2014-05-06 22:22:19">, #<Comment id: 2, post_id: 1, comment: "2", created_at: "2014-05-06 22:22:24", updated_at: "2014-05-06 22:22:24">]>
2.1.1 :010 > Post.joins(:comments).find(1,2)
Post Load (0.2ms) SELECT "posts".* FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id" WHERE "posts"."id" IN (1, 2)
ActiveRecord::RecordNotFound: Couldn't find all Posts with 'id': (1, 2) (found 5 results, but was looking for 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment