new + save 和 create 之间的 rails 差异 [英] Differences in rails between new + save and create
本文介绍了new + save 和 create 之间的 rails 差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 Rails 新手,不明白使用 new+save 方法和使用 create 方法之间的区别.
I'm new to rails and I don't understand the differences between the use of new+save methods and the create method.
def create
@item = Item.new(params[:item])
respond_to do |format|
if @item.save
format.html { redirect_to @item, notice: 'Item was successfully created.' }
format.json { render json: @item, status: :created, location: @item }
else
format.html { render action: "new" }
format.json { render json: @item.errors, status: :unprocessable_entity }
end
end
end
和:
def create
respond_to do |format|
if Item.create(params[:item])
format.html { redirect_to @item, notice: 'Item was successfully created.' }
format.json { render json: @item, status: :created, location: @item }
else
format.html { render action: "new" }
format.json { render json: @item.errors, status: :unprocessable_entity }
end
end
end
推荐答案
内部 create
调用 new
然后 save
无论如何:
Internally create
calls new
then save
anyway:
def create(attributes = nil, options = {}, &block)
if attributes.is_a?(Array)
attributes.collect { |attr| create(attr, options, &block) }
else
object = new(attributes, options, &block)
object.save
object
end
end
这篇关于new + save 和 create 之间的 rails 差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文