This project is archived and is in readonly mode.

#3188 new
Radosław Bułat

[ActiveRecord] create(:association_id => @object.id) vs create(:association_id => @object)

Reported by Radosław Bułat | September 11th, 2009 @ 08:44 AM

Lately I've encountered strange behavior of ActiveRecord. Suppose we have classic Post and Comment models (post has many comments, comment belongs to post). There are a few ways to create comment to given post. For example:

Comment.create(:post => @post)
Comment.create(:post_id => @post.id)

I made a mistake and mixed those two:

Comment.create(:post_id => @post)

In this case it always create Comment with post_id = 1 regardless of given Post object. It take me several hours to find this bug in my code and I think that it's not acceptable behavior.

I think that description is enough clear but for formality. How to reproduce:

$ rails -v Rails 2.3.4

$ rails bug && cd bug $ ./script/generate model Post title:string $ ./script/generate model Comment post:references title:string $ rake db:migrate $ ./script/console

first scenario (OK)

p1 = Post.create(:title => "1") Post Create (0.8ms) INSERT INTO "posts" ("updated_at", "title", "created_at") VALUES('2009-09-11 07:41:32', '1', '2009-09-11 07:41:32') => # p2 = Post.create(:title => "2") Post Create (0.5ms) INSERT INTO "posts" ("updated_at", "title", "created_at") VALUES('2009-09-11 07:41:37', '2', '2009-09-11 07:41:37') => # c1 = Comment.create(:title => "comment", :post => p2) Comment Create (1.3ms) INSERT INTO "comments" ("updated_at", "title", "post_id", "created_at") VALUES('2009-09-11 07:41:43', 'comment', 2, '2009-09-11 07:41:43') => # c1.post_id => 2

second scenario (OK)

c2 = Comment.create(:title => "comment", :post_id => p2.id) Comment Create (0.6ms) INSERT INTO "comments" ("updated_at", "title", "post_id", "created_at") VALUES('2009-09-11 07:42:35', 'comment', 2, '2009-09-11 07:42:35') => # c2.post_id => 2

third scenario (BAD)

c3 = Comment.create(:title => "comment", :post_id => p2) Comment Create (0.6ms) INSERT INTO "comments" ("updated_at", "title", "post_id", "created_at") VALUES('2009-09-11 07:42:54', 'comment', 1, '2009-09-11 07:42:54') => # c3.post_id => 1

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Pages