表单提交后重定向错误

时间:2018-01-16 22:13:04

标签: ruby-on-rails ruby validation

我开始学习Ruby了。我刚刚按照本指南http://guides.rubyonrails.org/getting_started.html创建了博客应用。有一件事我注意到,如果我们尝试提交表单而不从网址http://localhost:3000/articles/new输入数据,则会显示错误消息并重定向到http://localhost:3000/articles

我认为它应该保持相同的URL并显示错误消息。 不知道如何解决这个问题。

articles_controller.rb

class ArticlesController < ApplicationController

    def index
    @articles = Article.all
  end

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

    def new
        @article = Article.new
    end

    def create
        @article = Article.new(article_params)

      if @article.save
        redirect_to @article
      else
        render 'new'
      end 
  end   

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

end

new.html.erb

<%= form_with scope: :article, url: articles_path, local: true do |form| %>

  <% if @article.errors.any? %>
    <div id="error_explanation">
      <h2>
        <%= pluralize(@article.errors.count, "error") %> prohibited
        this article from being saved:
      </h2>
      <ul>
        <% @article.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <p>
    <%= form.label :title %><br>
    <%= form.text_field :title %>
  </p>

  <p>
    <%= form.label :text %><br>
    <%= form.text_area :text %>
  </p>

  <p>
    <%= form.submit %>
  </p>

<% end %>

<%= link_to 'Back', articles_path %>

的routes.rb

Rails.application.routes.draw do
  get 'welcome/index'

    resources :articles
    root 'welcome#index'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

rails routes

      Prefix Verb   URI Pattern                  Controller#Action
welcome_index GET    /welcome/index(.:format)     welcome#index
     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
         root GET    /                            welcome#index

2 个答案:

答案 0 :(得分:1)

这是标准行为。如果您想要更改它以保留网址,则可以修改newcreate操作:

def new
  if article_params
    create
    return
  end
  @article = Article.new
  render 'new'
end 

def create
  @article = Article.new(article_params)
  if @article.save
    redirect_to @article
  else
    render 'new'
  end
end

在routes.rb中:

resources :articles
post "articles/new"

答案 1 :(得分:1)

@Shannon回答是正确的,我写这篇文章是为了对你的回答发表评论,根据this当你要使用model时,尝试使用model: @article参数会自动为你生成一切

enter image description here

希望它有所帮助。