Forum: Ruby on Rails Mysterious associations

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
renek (Guest)
on 2006-12-29 16:20
(Received via mailing list)
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
Guest (Guest)
on 2006-12-29 17:05
I am no expert, but I would think it is because 5 is not a valid
datetime
renek (Guest)
on 2006-12-29 17:50
(Received via mailing list)
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
François B. (Guest)
on 2006-12-29 19:04
(Received via mailing list)
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/
This topic is locked and can not be replied to.