Rails 控制器创建 Model.new 和 Model.create 之间的动作差异 [英] Rails controller create action difference between Model.new and Model.create
问题描述
我正在学习一些 Rails 3 和 4 教程,并遇到了一些我希望得到的一些见解:
Model.new 和 Model.create 在 Create 操作方面有什么区别.我认为您确实在控制器中使用了 create
方法来进行保存,例如.@post = Post.create(params[:post])
但看起来我错了.任何见解都非常感谢.
使用 Post.new 创建动作
def new@post = Post.new结尾定义创建@post = Post.new(post_params)@post.save重定向到 post_path(@post)结尾def post_paramsparams.require(:post).permit(:title, :body)结尾
使用 Post.create 创建动作
def new@post = Post.new结尾定义创建@post = Post.create(post_params)@post.save重定向到 post_path(@post)结尾def post_paramsparams.require(:post).permit(:title, :body)结尾
我有两个问题
- 这是否与 Rails 4 的更改有关?
- 使用
@post = Post.create(post_params)
是不好的做法吗?
Model.new
以下实例化并初始化一个给定参数的 Post 模型:
@post = Post.new(post_params)
您必须运行 save
才能将您的实例保存在数据库中:
@post.save
模型.创建
以下实例化、初始化并在数据库中保存一个给定参数的 Post 模型:
@post = Post.create(post_params)
您不需要运行 save
命令,它已经内置了.
关于new
的更多信息这里>
关于create
的更多信息这里
I'm going through a few Rails 3 and 4 tutorial and come across something I would love some insights on:
What is the difference between the Model.new and Model.create in regards to the Create action. I thought you do use the create
method in the controller for saving eg. @post = Post.create(params[:post])
but it looks like I'm mistaken. Any insight is much appreciated.
Create action using Post.new
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
@post.save
redirect_to post_path(@post)
end
def post_params
params.require(:post).permit(:title, :body)
end
Create action using Post.create
def new
@post = Post.new
end
def create
@post = Post.create(post_params)
@post.save
redirect_to post_path(@post)
end
def post_params
params.require(:post).permit(:title, :body)
end
I have two questions
- Is this to do with a Rails 4 change?
- Is it bad practice to use
@post = Post.create(post_params)
?
Model.new
The following instantiate and initialize a Post model given the params:
@post = Post.new(post_params)
You have to run save
in order to persist your instance in the database:
@post.save
Model.create
The following instantiate, initialize and save in the database a Post model given the params:
@post = Post.create(post_params)
You don't need to run the save
command, it is built in already.
More informations on new
here
More informations on create
here
这篇关于Rails 控制器创建 Model.new 和 Model.create 之间的动作差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!