I've two models:
class User < ActiveRecord::Base
before_create :add_address
has_one :address
def add_address
self.address_id ||= Address.generate_new.id
end
end
And
class Address < ActiveRecord::Base
belongs_to :user
def self.generate_new
new_address = # some code generating UUID
Address.create!({address: new_address})
end
end
But when I create User, it saves address, but user_id didn't show on the Address model. I don't want to update Address after creating the User. Maybe I do smth not in a rails way?
But when I create User, it saves address, but user_id didn't show on the Address model.
The reason is your way to create new address is incorrect.
The correct way to build a new Address instance is through associated model User.
@address = @user.address.new("some params")
@address.save
In this way the instance address
will have user_id
inside automatically.
Two things more:
You don't need another generate_new
method, if the method does nothing but duplicate the functionality of save
, create
.
Optionally you can validate the presence of user_id in Address model, to ensure user_id is always valid before creating the Address object. It's optional because you can also ensure this as above
class Address < ActiveRecord::Base
belongs_to :user
validates_associated :user
end