ActiveRecord关系中的build和create方法有什么区别?

ber*_*kes 12 activerecord ruby-on-rails

我有一个可以有0或1个配置文件的用户.在我的Controller中,如果给出了一些值,我想保存配置文件,如下所示:

# 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
Run Code Online (Sandbox Code Playgroud)

我想知道的部分是create_profile魔术create_somerelationname.这与魔术相比如何build_somerelationname?什么时候应该使用哪个?

Veg*_*ger 17

build和之间的区别在于createcreate还保存了创建的对象,因为build只返回新创建的对象(尚未保存).

文档有点隐藏在这里.

因此,根据您是否对返回的对象感到满意,您需要create(因为您不再更改它),build因为您希望在再次保存之前更新它(这将节省您的保存操作)


fl0*_*00r 10

@user.build_profile 是相同的

Profile.new(:user_id => @user.id)
Run Code Online (Sandbox Code Playgroud)

虽然@user.create_profile是一样的

Profile.create(:user_id => @user.id)
Run Code Online (Sandbox Code Playgroud)

@user.create_profile可以build_profile像这样呈现:

profile = @user.build_profile
profile.save
Run Code Online (Sandbox Code Playgroud)

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


Sye*_*lam 7

指南

build_association(attributes = {})

build_association方法返回关联类型的新对象.此对象将从传递的属性实例化,并且将设置通过其外键的链接,但是尚未保存关联的对象.

create_association(attributes = {})

create_association方法返回关联类型的新对象.此对象将从传递的属性实例化,并将设置通过其外键的链接.此外,将保存关联的对象(假设它通过任何验证).

你应该使用什么取决于要求.通常build_association用于新方法.