加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 为什么rails在创建后会重定向到show动作?

发布时间:2020-12-17 03:49:33 所属栏目:百科 来源:网络整理
导读:这里是新的Web开发人员,我想我可能会遗漏一些非常基础的知识. 鉴于代码 def create @post = Post.new(post_params) if @post.save redirect_to @post else render "new" endend 为什么视图模板重定向到def show动作?如果我没有定义def show及其相应的视图,r
这里是新的Web开发人员,我想我可能会遗漏一些非常基础的知识.
鉴于代码

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,它似乎在创建帖子后重定向到显示页面.这只是其中之一,我应该把它当作它,或者我错过了一些基本的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.

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

if @post.save
  redirect_to @post

当@post成功保存时,我们通过编写redirect_to @post重定向它来显示动作,show动作的实际路径是post_path(@post),所以你也可以写redirect_to post_path(@post),但即使你只是通过带有redirect_to rails的对象会将其重定向到show动作.现在去其他部分

else
  render "new"

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

希望这有帮助!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读