我有一个可以拥有0或1个个人资料的用户。在我的控制器中,如果要提供某些值,我想保存配置文件,如下所示:
# 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
我想知道的部分是
create_profile
,魔术create_somerelationname
。与魔术build_somerelationname
相比有什么不同?那我什么时候该用呢? 最佳答案
build
和create
之间的区别在于,create也保存创建的对象,因为build仅返回新创建的对象(尚未保存)。
该文档在here中有些隐藏。
因此,根据您是否对返回的对象感到满意,分别需要create
(因为您将不再更改它)build
,因为您要在再次保存之前对其进行更新(这将为您节省保存操作)
关于ruby-on-rails - ActiveRecord关系中的build和create方法之间有什么区别?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7024301/