Mysterious associations


#1

I have a issue with simple associations which I cannot explain. I have
created a simple model Post with two attributes ‘name’ and ‘date’. I
use the following migration:

class CreatePosts < ActiveRecord::Migration
def self.up
create_table :posts do |t|
t.column :name, :string
t.column :date, :datetime
end
end

def self.down
drop_table :posts
end
end

In the console I create a new Post:

p = Post.new
=> #<Post:0xb79aa788 @new_record=true, @attributes={“name”=>nil,
“date”=>nil}>

Then I assign the value “5” to both name and date:

p.name = “5”
=> “5”

p.date = “5”
=> “5”

And check the assignments:

p
=> #<Post:0xb79aa788 @new_record=true, @attributes={“name”=>“5”,
“date”=>“5”}>

p.name
=> “5”

p.date
=> nil

Why does the object p have the attributes both set to “5” but when I
use the association it turns up with nil for the associated date.

Can anybody explain this?

Thanks,
Ren


#2

I am no expert, but I would think it is because 5 is not a valid
datetime


#3

I know the string “5” is not a valid datetime. My question is why the
string shows up in the inspection of the object:

p
=> #<Post:0xb79aa788 @new_record=true, @attributes={“name”=>“5”,
“date”=>“5”}>

but is not accessible:

p.date
=> nil

p.send(:date)
=> nil

p.attributes
=> {“name”=>“5”, “date”=>nil}

Cheers,
Ren


#4

Hi,

2006/12/29, renek removed_email_address@domain.invalid:

I know the string “5” is not a valid datetime. My question is why the
string shows up in the inspection of the object:

p
=> #<Post:0xb79aa788 @new_record=true, @attributes={“name”=>“5”,
“date”=>“5”}>

but is not accessible:

p.date
=> nil

ActiveRecord knows to cast the attribute to a date before returning
the value. Since the value can’t be cast, it returns nil.

When you call date on p, you are actually calling a whole series of
methods, not just a simple getter.

Hope that helps !

François Beausoleil
http://blog.teksol.info/
http://piston.rubyforge.org/