为什么 rails 创建后重定向到 show 动作?
Why does rails redirect to the show action after creating?
这里是网络开发新手,我想我可能缺少一些非常基础的知识。
给定代码
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post
else
render "new"
end
end
为什么视图模板重定向到 def show 操作?如果我没有定义 def show 及其相应的视图,rails 将抛出一个错误。
我只是不明白为什么即使代码是 redirect_to @post 在我保存 post 之后,它似乎创建 post 后重定向到显示页面。这只是我应该按原样接受的那些 rails 事情之一,还是我缺少一些基本的 HTML 协议知识(老实说我不太了解)?
编辑:为了进一步澄清我的问题,我看到 @post 已经在 create 方法中定义并且定义为 Post.new(post_params). 当我 redirect_to @post,它不会简单地再次调用该行吗?
让我们看看你的代码
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post
else
render "new"
end
end
why does the view templates redirect to the def show action? If I do not define a def show and its corresponding views, rails will throw me an error.
在 create
操作中,您正在创建一条新记录,所以如果您查看这部分代码
if @post.save
redirect_to @post
当 @post
成功保存后,我们将通过写入 redirect_to @post
将其重定向以显示操作,show
操作的实际路径将是 post_path(@post)
因此您可以也写 redirect_to post_path(@post)
但即使你只是用 redirect_to
传递对象 rails 也会将它重定向到 show 动作。现在转到 else
部分
else
render "new"
如果 @post
对象没有保存在数据库中(由于验证),我们要重新加载表单,所以在上面的代码中 render
只是渲染 [= 的视图23=] 操作而不调用 new
操作,只呈现视图,因为 new.html.erb
包含表单。
希望对您有所帮助!
这里是网络开发新手,我想我可能缺少一些非常基础的知识。 给定代码
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post
else
render "new"
end
end
为什么视图模板重定向到 def show 操作?如果我没有定义 def show 及其相应的视图,rails 将抛出一个错误。
我只是不明白为什么即使代码是 redirect_to @post 在我保存 post 之后,它似乎创建 post 后重定向到显示页面。这只是我应该按原样接受的那些 rails 事情之一,还是我缺少一些基本的 HTML 协议知识(老实说我不太了解)?
编辑:为了进一步澄清我的问题,我看到 @post 已经在 create 方法中定义并且定义为 Post.new(post_params). 当我 redirect_to @post,它不会简单地再次调用该行吗?
让我们看看你的代码
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post
else
render "new"
end
end
why does the view templates redirect to the def show action? If I do not define a def show and its corresponding views, rails will throw me an error.
在 create
操作中,您正在创建一条新记录,所以如果您查看这部分代码
if @post.save
redirect_to @post
当 @post
成功保存后,我们将通过写入 redirect_to @post
将其重定向以显示操作,show
操作的实际路径将是 post_path(@post)
因此您可以也写 redirect_to post_path(@post)
但即使你只是用 redirect_to
传递对象 rails 也会将它重定向到 show 动作。现在转到 else
部分
else
render "new"
如果 @post
对象没有保存在数据库中(由于验证),我们要重新加载表单,所以在上面的代码中 render
只是渲染 [= 的视图23=] 操作而不调用 new
操作,只呈现视图,因为 new.html.erb
包含表单。
希望对您有所帮助!