Alex Rivera | Logout

What is the difference between the build and create method in ActiveRecord relations?

Asked 2011-08-11T10:28:58.600
17

I have a User who can have 0 or 1 Profiles. In my Controller, I want to save the profile if some of the values are given, as follows:

# PUT /users/1
def update
  @user = User.find(params[:id])

  if @user.update_attributes(params[:user])
    if params[:profile][:available] == 1 #available is a checkbox that stores a simple flag in the database.
      @user.create_profile(params[:profile])
    end
  else 
    #some warnings and errors
  end
end

The part I am wondering about is create_profile, the magic create_somerelationname. How does that compare to the magic build_somerelationname? And when should I use which?

Edit
Report

1 Answer

9

From the guide

build_association(attributes = {})

The build_association method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will not yet be saved.

create_association(attributes = {})

The create_association method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set. In addition, the associated object will be saved (assuming that it passes any validations).

What you should use depends on the requirement. Generally the build_association is used in the new method.

answered 2011-08-11T10:37:54.150

Your Answer