Created
June 12, 2014 10:07
-
-
Save aruprakshit/34c8ce8eacbcb864f24c to your computer and use it in GitHub Desktop.
Confusion with Rails belongs_to association
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#------model definition----- | |
class Book < ActiveRecord::Base | |
end | |
class Page < ActiveRecord::Base | |
belongs_to :book | |
end | |
#------migration---------- | |
class CreateBooks < ActiveRecord::Migration | |
def change | |
create_table :books do |t| | |
t.string :name | |
t.string :author_name | |
t.timestamps | |
end | |
end | |
end | |
class CreatePages < ActiveRecord::Migration | |
def change | |
create_table :pages do |t| | |
t.integer :page_number | |
t.integer :book_id | |
t.timestamps | |
end | |
end | |
end | |
#------------------------------- | |
# I used the `#book_build` method. | |
2.1.2 :058 > new_book = page.build_book(:name => 'Ruby science II') | |
=> #<Book id: nil, name: "Ruby science II", author_name: nil, created_at: nil, updated_at: nil> | |
# as book is created in memory, but not saved in DB, thus book_id is nil. I got it. | |
2.1.2 :059 > page.book | |
=> #<Book id: nil, name: "Ruby science II", author_name: nil, created_at: nil, updated_at: nil> | |
# Now I saved it to the DB. | |
2.1.2 :060 > new_book.save | |
(0.1ms) begin transaction | |
SQL (0.2ms) INSERT INTO "books" ("created_at", "name", "updated_at") VALUES (?, ?, ?) [["created_at", "2014-06-12 09:58:22.539135"], ["name", "Ruby science II"], ["updated_at", "2014-06-12 09:58:22.539135"]] | |
(0.9ms) commit transaction | |
=> true | |
# as the record is got saved to DB, thus id got value as 5 | |
2.1.2 :061 > page.book | |
=> #<Book id: 5, name: "Ruby science II", author_name: nil, created_at: "2014-06-12 09:58:22", updated_at: "2014-06-12 09:58:22"> | |
# Now my question is why the book_id is still nil in the page object ? | |
2.1.2 :062 > page | |
=> #<Page id: 2, page_number: nil, book_id: nil, created_at: "2014-06-12 09:51:52", updated_at: "2014-06-12 09:51:52"> | |
2.1.2 :063 > Page.find(2) | |
Page Load (0.2ms) SELECT "pages".* FROM "pages" WHERE "pages"."id" = ? LIMIT 1 [["id", 2]] | |
=> #<Page id: 2, page_number: nil, book_id: nil, created_at: "2014-06-12 09:51:52", updated_at: "2014-06-12 09:51:52"> | |
2.1.2 :064 > |
Author
aruprakshit
commented
Jun 12, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment