【发布时间】:2013-07-31 07:02:17
【问题描述】:
我正在阅读一些 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)是不好的做法吗?
【问题讨论】:
-
Rails new vs create 的可能重复项
-
感谢 Amadan 的参考。
GET和POST的 Rails REST 实现是否与控制器操作new和create相同?我试图澄清 REST 与控制器操作与控制器方法。 -
对不起,我应该澄清一下; Justin Ethier 的回答特别提到了 ActiveRecord 方法。
标签: ruby-on-rails ruby-on-rails-3.2 ruby-on-rails-4