Reputation: 15501
What would be the correct rails way to create a row in the Database upon creation?
For example you have a User model where you create a new User
User.rb model
user_id
user_id =1
Now Im look for a way to create a new object / row in Database for other models for example
Account.rb model
Should create a new row in account table with user_id = same as user_id above
Currently I use a
= f.fields_for :profile do |f|
= f.text_field :some_value_for_profile
Inside my User create view so that some values are written to the database upon User creation but this is not the "rails way" and would like to use ActiveRecord hooks to do this instead.
Upvotes: 0
Views: 478
Reputation: 5914
If you are collecting the data for Account model from the view, you should create the account record with user record.
Assuming there is a has one relationship between both(user has_one account)
#in controller
@user = User.new params[:users]
@account = @user.build_account params[:account]
@user.save
Otherwise, if you are trying to create a default account record for all new users without collecting account data at the time of user registration, you can have a after_create callback
#in user.rb
after_create :add_account
def add_account
self.create_account
end
Upvotes: 1