Forum: Ruby on Rails activerecord failed?

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.
F78258e63d2879413ebf4558d74c1a9e?d=identicon&s=25 Kevin Yang (Guest)
on 2007-03-27 15:00
(Received via mailing list)
Hello all,
    i found something wrong (or maybe i was wrong?)
    this looks like a rectiverecord bug , can anyone help me to point
out what's going on?


------------------migration
    create_table :books do |t|
      t.column :name,:string
      t.column :person_id,:integer
    end

    create_table :people do |t|
      t.column :name ,:string
    end
------------------model
class Book < ActiveRecord::Base
  belongs_to :person
end

class Person < ActiveRecord::Base
  has_many :books
end

------------------in console , try the following:

book=Book.create(:name=>'book1')
kevin=Person.create(:name=>'kevin')
kevin.books  # should be empty []

book.person=kevin
book.save

kevin.books  # why still nothing ???


Person.find(kevin.id).books # have books!
A2c85dc5ee81b12e3cc0a6522e8d079d?d=identicon&s=25 Chris Hall (au5lander)
on 2007-03-27 15:43
(Received via mailing list)
because you already loaded the association when you did kevin.books
the first time.

book = Book.create(...)
kevin - Person.create(...)
kevin.books # empty, now association is loaded, it won't be reloaded
unless you force it

book.person = kevin
book.save

kevin.books(true) # passing true forces reload, should show associated
books
391f9b787cdc12aa2c179713f5103e3a?d=identicon&s=25 Ilan Berci (iberci)
on 2007-03-27 15:45
>
> book=Book.create(:name=>'book1')
> kevin=Person.create(:name=>'kevin')
> kevin.books  # should be empty []
>
> book.person=kevin
> book.save
>
> kevin.books  # why still nothing ???
>
>
> Person.find(kevin.id).books # have books!

kevin.reload
This topic is locked and can not be replied to.