[英]Saving a newly-created object
In a Rails controller code 在Rails控制器代码中
def create
@post = Post.new(params[:post])
@post.random_hash = generate_random_hash(params[:post][:title])
if @post.save
format.html { redirect_to @post }
else
format.html { render action: "new" }
end
end
Should the first two lines of the definition be put inside if @post.save
or not? if @post.save
与否,定义的前两行是否应该放在里面? If the post is not saved, will the Post object created by Post.new
still be put in the database? 如果帖子未保存,
Post.new
创建的Post对象Post.new
仍会被放入数据库?
Should the first two lines of the definition be put inside if
@post.save
or not?如果
@post.save
与否,定义的前两行是否应该放在里面?
Most certainly not. 当然不是。 If you change it to the following as you suggest:
如果您按照建议将其更改为以下内容:
def create if @post.save @post = Post.new(params[:post]) @post.random_hash = generate_random_hash(params[:post][:title]) format.html { redirect_to @post } else format.html { render action: "new" } end end
Then it won't work at all. 然后它根本不起作用。 There is no
@post
to call save
on. 没有
@post
来调用save
。
If the post is not saved, will the
Post
object created byPost.new
still be put in the database?如果帖子未保存,
Post.new
创建的Post
对象Post.new
仍会被放入数据库?
Of course not. 当然不是。 That's what saving does: saves the object in the database.
这就是保存的作用:将对象保存在数据库中。 If you don't call
save
on the Post
object, or the save
returns false
(which would happen because a validation failed), the object was not stored in the database. 如果不在
Post
对象上调用save
,或者save
返回false
(由于验证失败而发生),则该对象未存储在数据库中。 Post.new
simply creates a new Post
object in-memory—it doesn't touch the database at all. Post.new
只是在内存中创建一个新的Post
对象 - 它根本不会触及数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.