开发者

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

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 wh开发者_如何学Pythonich?


The difference between build and create is that create also saves the created object as build only returns the newly created object (without it being saved yet).

The documentation is somewhat hidden away here.

So, depending whether you are happy with the returned object or not, you need create (since you will not change it anymore) respectively build as you want to update it before saving again (which will save you a save operation)


@user.build_profile is the same as

Profile.new(:user_id => @user.id)

while @user.create_profile is the same as

Profile.create(:user_id => @user.id)

@user.create_profile can be presented with build_profile like this:

profile = @user.build_profile
profile.save

http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_one


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜