【问题标题】:Ruby - redirect_to redirects to the correct page, but isn't changing the URLRuby - redirect_to 重定向到正确的页面,但不更改 URL
【发布时间】:2016-03-18 18:20:40
【问题描述】:

我正在自学 Ruby 和 Rails……直到今天,我对它的感觉还不错。 :)

但是,今天我遇到了一个我似乎无法解决的问题。我正在通过创建博客来练习。我设置了路线和视图 - 代码将写入数据库 - 但 redirect_to 似乎无法正常工作。

如果用户导航到:.../article/new,他们可以输入新文章。提交成功后,应用应重定向到 URL ../article/id,在 show.html.erb 上显示文章并闪烁一条消息,表明文章已成功保存。

由于某种原因,我无法使 URL 重定向部分正常工作。文章保存,show.html.erb 显示正确的消息...但 url 保持 ../article/new。如果重定向不起作用,则应用程序的其余部分将不起作用,因为其他操作需要不同的 URL(例如../article/id/edit)。

我一直在用

 在显示页面上,看起来一切都已正确保存(我怀疑这是因为它调用了正确的视图)。

任何想法都会非常非常受欢迎。能够学习 Ruby 和 Rails,我真的很兴奋,并期待着度过难关。

articles_controller.rb:

class ArticlesController < ApplicationController
  def new
    @article = Article.new
  end

  def create
    @article = Article.new(article_params)
    if @article.save
      flash[:notice] = "Article was successfully created"
      redirect_to article_path(@article)
    else
      render 'new'
    end
  end

  def show
    @article = Article.find(params[:id])
  end

  private
  def article_params
    params.require(:article).permit(:title, :description)
  end
end

耙路线:

Prefix Verb   URI Pattern                  Controller#Action
        root GET    /                            pages#home
       about GET    /about(.:format)             pages#about
    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

【问题讨论】:

  • 您在应用程序中使用 turbolinks 吗?
  • 我不...我只是 cloud 9 的 IDE 预装的任何东西。

标签: ruby-on-rails ruby


【解决方案1】:

您是否尝试将article_path 更改为article_url?这可能会触发您正在寻找的行为。

【讨论】:

  • 嗨 - 我刚试过这个,但没有用。我真的,真的很茫然...我一直在学习本教程,一切都很好,直到我遇到这个问题...
【解决方案2】:

在四处寻找之后,cloud9 论坛的一位友好用户能够帮助我解决这个问题。我在 c-9 窗口中运行应用程序...在实际浏览器窗口中运行它解决了问题。

这是在 cloud9 论坛上发现的对话链接:

https://community.c9.io/t/ruby-rails-redirect-to-not-working-properly/3644

再次感谢 Oxyrus 帮助我解决这个问题。

【讨论】:

    猜你喜欢
    • 2019-03-09
    • 1970-01-01
    • 2014-02-20
    • 2017-02-24
    • 1970-01-01
    • 2013-10-12
    • 2014-09-17
    • 1970-01-01
    • 2014-09-29
    相关资源
    最近更新 更多