Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: what does build_model do?

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
like image 689
TimmyOnRails Avatar asked Jan 15 '23 06:01

TimmyOnRails


1 Answers

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

like image 126
Ian Armit Avatar answered Jan 22 '23 09:01

Ian Armit