Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 为什么rails在创建后重定向到show操作?_Ruby On Rails_Rails Routing - Fatal编程技术网

Ruby on rails 为什么rails在创建后重定向到show操作?

Ruby on rails 为什么rails在创建后重定向到show操作?,ruby-on-rails,rails-routing,Ruby On Rails,Rails Routing,这里是新的web开发人员,我想我可能缺少一些非常基础的知识。 给定代码 def create @post = Post.new(post_params) if @post.save redirect_to @post else render "new" end end 为什么视图模板重定向到def show操作?如果我没有定义一个def show及其相应的视图,rails将抛出一个错

这里是新的web开发人员,我想我可能缺少一些非常基础的知识。 给定代码

def create
        @post = Post.new(post_params)
        if @post.save
            redirect_to @post
        else
            render "new"
        end
end
为什么视图模板重定向到def show操作?如果我没有定义一个def show及其相应的视图,rails将抛出一个错误

我只是不明白为什么在我保存一篇文章后,代码被重定向到@post,但在创建一篇文章后,它似乎被重定向到显示页面。这仅仅是rails中我应该接受的东西之一,还是我缺少了一些基本的HTML协议知识(我真的不太了解)


编辑:为了进一步澄清我的问题,我看到@post已经在create方法中定义,并被定义为post.new(post_参数)。当我重定向到@post时,它不会简单地再次调用该行吗?

让我们看看您的代码

def create
  @post = Post.new(post_params)
  if @post.save
    redirect_to @post
  else
    render "new"
  end
end
为什么视图模板重定向到def show操作?如果我没有定义def show及其相应的视图,rails将抛出一个错误

create
操作中,您正在创建一条新记录,因此如果您查看代码的这一部分

if @post.save
  redirect_to @post
@post
成功保存后,我们通过写入
重定向到@post
将其重定向到显示操作,
show
操作的实际路径将是
post\u路径(@post)
,因此您也可以将
重定向到post\u路径(@post)
但即使您只是将对象通过
redirect\u传递到
rails,它也会重定向到show操作。现在转到
else
部分

else
  render "new"
如果
@post
对象未保存在数据库中(由于验证),我们希望重新加载表单,因此在上面的代码
render
中,只是呈现
new
操作的视图,而不调用
new
操作,只呈现视图,因为
new.html.erb
包含表单


希望这有帮助

谢谢你的解释!如果我错了,请纠正我,但这是否意味着你将始终返回到表演动作?我可以重定向到其他位置吗?当然可以,请尝试
重定向到“http://google.com“
相反,它将重定向到
google
,您可以通过重定向传递任何
url
。我的
代码与OP完全相同,但如果
块为空,它仍将我重定向到创建页面,为什么会这样?