1

In my project, a user has a hotel, and each hotel has room types associated with it. Briefly, the models are

 class User < ActiveRecord::Base
     has_many :hotels

 class Hotel < ActiveRecord::Base
      belongs_to :user
      has_many :roomtypes

 class Roomtype < ActiveRecord::Base
    attr_accessible :maxguests, :name
    belongs_to :hotel

If I do the commands:

 @user = User.find(1)
 @user.hotels.find(1).roomtypes.build(name: "something", maxguests: "2")

The console returns:

    #<Roomtype id: nil, name: "something", maxguests: 2, created_at: nil, updated_at: nil, hotel_id: 1> 

For some reason, the Roomtype id and the timestamps are nil. Any ideas why?

Tim Reistetter
  • 829
  • 1
  • 12
  • 17

2 Answers2

7

You have built the roomtype (which creates a new instance of the object), but you not saved it yet. You have to explicitly save roomtype for it to go into the db (and thus get an id).

Instead of build use create or create! to accomplish this with a single method call

Taryn East
  • 27,486
  • 9
  • 86
  • 108
Amar
  • 6,874
  • 4
  • 25
  • 23
  • See http://stackoverflow.com/questions/403671/the-differences-between-build-create-and-create-and-when-should-they-be-us for a more detailed description of these methods. – gregates Sep 11 '12 at 13:59
3

Replace build with create and you'll have your persisted object with id and timestamp.

Would not make sense to have this before.

apneadiving
  • 114,565
  • 26
  • 219
  • 213