我正在浏览一些 Rails 3 和 4 教程,并发现了一些我想要的见解:
Model.new 和 Model.create 在创建操作方面有什么区别?我以为你确实使用了create
控制器中的保存方法,例如。@post = Post.create(params[:post])
但看来我错了。任何见解都非常感激。
使用 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
使用 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
我有两个问题
- 这与 Rails 4 的更改有关吗?
- 使用是不好的做法吗
@post = Post.create(post_params)
?
型号.new
以下实例化并初始化给定参数的 Post 模型:
@post = Post.new(post_params)
你必须跑save
为了将您的实例保留在数据库中:
@post.save
模型.创建
下面实例化、初始化and save在数据库中,给定参数的 Post 模型:
@post = Post.create(post_params)
你不需要运行save
命令,它已经内置了。
有关更多信息new
here http://apidock.com/rails/ActiveRecord/Base/new/class
有关更多信息create
here http://apidock.com/rails/ActiveRecord/Base/create/class/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)