I am not quite prepared to call this a rails bug. But has_one definitely behaves weirdly in rails 2.1.

Lets say you have the following two models:

class Email < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_one :email
end

A very straight forward has_one association. Now give the following from a script/console session:

>> user = User.first
=> #<User id: 1, created_at: "2008-07-09 01:19:11", updated_at: "2008-07-09 01:19:11">
>> user.email = Email.find(user.email.id)
=> #<Email id: 1, user_id: 1, created_at: "2008-07-09 01:19:26", updated_at: "2008-07-09 01:19:26">
>> user.reload
=> #<User id: 1, created_at: "2008-07-09 01:19:11", updated_at: "2008-07-09 01:19:11">
>> user.email
=> nil

That is weird. There is no reason you would do this in production, but if you were doing this you wouldn’t expect it to update the email row to set user_id to nil. Unfortunately, that is exactly what is happening.

Personally, I wouldn’t expect it to write anything to the database until I called save on user.

Anyone have a reasonable explanation, or should I submit it to Lighthouse.

Post Information

Tags:

We're Reading

Feeds/Syndication

2 Responses to “has_one weirdness”

Leave a Reply