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

ruby-on-rails – redirect_to方法如何在ruby中工作

发布时间:2020-12-17 04:01:43 所属栏目:百科 来源:网络整理
导读:这是我的更新功能,当一些内容更新时,它完全转到http:// localhost:3000 / articles / 2 def update @article = Article.find(params[:id]) if @article.update(article_params) redirect_to @article else render 'edit' end end redirect_to @article如何
这是我的更新功能,当一些内容更新时,它完全转到http:// localhost:3000 / articles / 2

def update
    @article = Article.find(params[:id])
    if @article.update(article_params)
      redirect_to @article
    else
      render 'edit'
    end
  end

redirect_to @article如何工作并显示artiles / 2 /页面?

以下是我的路线

Prefix Verb   URI Pattern                  Controller#Action
     articles GET    /articles(.:format)          articles#index
              POST   /articles(.:format)          articles#create
  new_article GET    /articles/new(.:format)      articles#new
 edit_article GET    /articles/:id/edit(.:format) articles#edit
      article GET    /articles/:id(.:format)      articles#show
              PATCH  /articles/:id(.:format)      articles#update
              PUT    /articles/:id(.:format)      articles#update
              DELETE /articles/:id(.:format)      articles#destroy
welcome_index GET    /welcome/index(.:format)     welcome#index
         root GET    /                            welcome#index

解决方法

magic方法是polymorphic_url.

当你调用link_to,redirect_to等而你没有传递字符串或路由选项的散列时,Rails最终会调用这个方法.

Active Record(和Active Model兼容对象)有一个model_name类方法,它返回一个ActiveMethod :: Name对象,该对象有一堆方法可以为各种用途获取模型类的“正确”名称.

其中一个(singular_route_key)说明路径中的模型使用了什么名称.如果你在引擎中,这也会处理像命名空间这样的事情.

在最简单的情况下,归结为

@article.class.model_name.singular_route_key #=> 'article'

然后Rails通过将其与任何前缀选项和正确的后缀(‘url’,’path’等)连接起来,从而生成方法名称,最后得到一个方法名称,如article_url.然后它调用该方法(根据您的路由文件为您生成),传递文章,该文章返回本文的URL.

(编辑:李大同)

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

    推荐文章
      热点阅读