I have a user and profile models and I use the same form to populate them. In my controller I have the line: @user.build_profile
I would like to know what does this line do. The relationship between user and profile is one-to-one, and profile belong to user.
I also have a new model called image, I would like to set up a one-to-many relationship with user, using nested attributes. In my new action in the user coltroller, should I use a similar line like the one above? @user.build_image
The complete new action:
def new
@user = User.new
@user.build_profile
respond_to do |format|
format.html # new.html.erb
format.json { render json: @user }
end
end
build_profile will create an empty profile object(which will belong to @user). Later on in the create action you will call
@user.save
which will save the profile (along with the user) into the database.
http://guides.rubyonrails.org/association_basics.html -explains it
edit: For a has_many relation you would call
@user.images.build
to create a new image model. This rail cast goes over it
http://railscasts.com/episodes/196-nested-model-form-part-1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With