Ruby on rails 保存新创建的对象
在Rails控制器代码中Ruby on rails 保存新创建的对象,ruby-on-rails,ruby-on-rails-3.2,Ruby On Rails,Ruby On Rails 3.2,在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 定义的前两行是否应该放在@
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
定义的前两行是否应该放在@post.save中?如果未保存post,由post.new
创建的post对象是否仍会放入数据库中
如果@post.save
,定义的前两行是否应该放在里面
当然不是。如果按照您的建议将其更改为以下内容:
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
那就根本不起作用了。没有@post
可以调用save
如果未保存帖子,由post.new创建的post
对象是否仍会放入数据库中
当然不是。这就是保存的作用:将对象保存到数据库中。如果未在Post
对象上调用save
,或者save
返回false
(由于验证失败而发生),则该对象未存储在数据库中Post.new
只是在内存中创建一个新的Post
对象,它根本不涉及数据库
如果@post.save
,定义的前两行是否应该放在里面
当然不是。如果按照您的建议将其更改为以下内容:
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
那就根本不起作用了。没有@post
可以调用save
如果未保存帖子,由post.new创建的post
对象是否仍会放入数据库中
当然不是。这就是保存的作用:将对象保存到数据库中。如果未在Post
对象上调用save
,或者save
返回false
(由于验证失败而发生),则该对象未存储在数据库中Post.new
只是在内存中创建一个新的Post
对象,它根本不涉及数据库