簡體   English   中英

Rails 使用 micropost 腳手架時不呈現錯誤頁面

[英]Rails does not render error page when using micropost scaffold

我正在關注 Rails 教程上的 Ruby,但我似乎對沒有呈現所描述的錯誤頁面的驗證練習感到困惑。

使用命令后

rails generate scaffold Micropost content:text user_id:integer

在 apps-->models--micropost.rb 的 micropost model 中添加以下驗證

validates :content, length: { maximum: 140 }

該應用程序應該阻止超過 140 個字符的新消息發布,並引發錯誤頁面。 驗證部分似乎成功並阻止消息保存在數據庫中,但錯誤頁面似乎沒有在 Chrome 檢查器中呈現為驗證,它只顯示表單字段。

這些是我為調試它而執行的步驟。

  1. 使用 Chrome 檢查器檢查頁面
    結果:頁面似乎卡在表單和輸入頁面上,而不是呈現默認的 rails 錯誤頁面,如教程中所述。

  2. 檢查 config-->environments-->development.rb 文件中的以下行:

    config.consider_all_requests_local = true

  3. 檢查了 microposts controller 文件,該文件似乎有一個應該呈現錯誤頁面的分支,相關代碼如下所示:

    def create
        @micropost = Micropost.new(micropost_params)
    
        respond_to do |format|
          if @micropost.save
            format.html { redirect_to @micropost, notice: 'Micropost was successfully created.' }
            format.json { render :show, status: :created, location: @micropost }
          else
            format.html { render :new }
            format.json { render json: @micropost.errors, status: :unprocessable_entity }
          end
        end
      end
  1. 檢查顯示表單的 micropost 視圖並驗證它是否應該顯示錯誤(如果存在)。
    視圖具有以下代碼:

     <%= form_with(model: micropost) do |form| %> <% if micropost.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(micropost.errors.count, "error") %> prohibited this micropost from being saved:</h2> <ul> <% micropost.errors.each do |error| %> <li><%= error.full_message %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= form.label:content %> <%= form.text_area:content %> </div> <div class="field"> <%= form.label:user_id %> <%= form.number_field:user_id %> </div> <div class="actions"> <%= form.submit %> </div> <% end %> ```
  2. 恢復到原始代碼,刪除數據庫並重新按照步驟驗證輸入正確的代碼。

結果是一樣的。 還應該注意的是,我已經看到 rails 顯示的其他默認錯誤頁面,這使我相信在此應用程序的開發版本中打開了錯誤頁面。

使用 Rails 版本 6.1.3 和第 6 版 Ruby on rails 教程由 Micheal Hartl

編輯:看起來應用程序正在正確地捕獲驗證測試。 @micropost.errors.full_messages返回的錯誤消息應該在頁面上顯示。 (byebug) @micropost.errors.full_messages ["Content is too long (maximum is 140 characters)"] (byebug) “新”視圖看起來像我在原始頁面中描述為表單頁面的頁面上顯示的內容郵政。 (減去錯誤字符串)

<%= render 'form', micropost: @micropost %>

<%= link_to 'Back', microposts_path %>

@dakota-lee-martinez

我剛剛注意到您提到的代碼格式為.html.erb 文件,由腳手架創建

  <% if micropost.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(micropost.errors.count, "error") %> prohibited this micropost from being saved:</h2>

      <ul>
        <% micropost.errors.each do |error| %>
          <li><%= error.full_message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

這很奇怪,因為我們可以看到實例值 @micropost.errors.full_message 加載了錯誤消息。

附加信息:我剛剛在終端 window 中注意到 rails 服務器正在運行,我相信它表明它已經呈現了我們一直在談論的兩個頁面。

這是 output:

Rendering layout layouts/application.html.erb
  Rendering microposts/new.html.erb within layouts/application
  Rendered microposts/_form.html.erb (Duration: 4.0ms | Allocations: 1769)

這是 _form.html.erb 在 Chrome 檢查器元素選項卡中呈現的內容:

    <h1>New Micropost</h1>

<form action="/microposts" accept-charset="UTF-8" data-remote="true" method="post"><input type="hidden" name="authenticity_token" value="54yHyZB7szu9XL3lVvPOAhTJbKC4ghs9bJ+PDNCHuk/0+nUX37J1jvrmtamMGMXDu1flt3mWORlUdkRyzLBcCw==">

  <div class="field">
    <label for="micropost_content">Content</label>
    <textarea name="micropost[content]" id="micropost_content"></textarea>
  </div>

  <div class="field">
    <label for="micropost_user_id">User</label>
    <input type="number" name="micropost[user_id]" id="micropost_user_id">
  </div>

  <div class="actions">
    <input type="submit" name="commit" value="Create Micropost" data-disable-with="Create Micropost">
  </div>
</form>

完整的服務器日志:

=> Booting Puma
=> Rails 6.1.3 application starting in development 
=> Run `bin/rails server --help` for more startup options
Puma starting in single mode...
* Puma version: 5.2.2 (ruby 2.6.3-p62) ("Fettisdagsbulle")
*  Min threads: 5
*  Max threads: 5
*  Environment: development
*          PID: 29318
* Listening on http://127.0.0.1:8080
* Listening on http://[::1]:8080
Use Ctrl-C to stop
Started GET "/" for 107.77.219.209 at 2021-03-08 21:23:03 +0000
Cannot render console from 107.77.219.209! Allowed networks: 127.0.0.0/127.255.255.255, ::1
   (1.5ms)  SELECT sqlite_version(*)
   (0.2ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
Processing by UsersController#index as HTML
  Rendering layout layouts/application.html.erb
  Rendering users/index.html.erb within layouts/application
  User Load (0.2ms)  SELECT "users".* FROM "users"
  ↳ app/views/users/index.html.erb:15
  Rendered users/index.html.erb within layouts/application (Duration: 11.0ms | Allocations: 4854)
[Webpacker] Everything's up-to-date. Nothing to do
  Rendered layout layouts/application.html.erb (Duration: 46.6ms | Allocations: 10877)
Completed 200 OK in 62ms (Views: 50.7ms | ActiveRecord: 0.7ms | Allocations: 13882)


Started GET "/" for 107.77.219.209 at 2021-03-08 21:23:05 +0000
Cannot render console from 107.77.219.209! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by UsersController#index as HTML
  Rendering layout layouts/application.html.erb
  Rendering users/index.html.erb within layouts/application
  User Load (0.1ms)  SELECT "users".* FROM "users"
  ↳ app/views/users/index.html.erb:15
  Rendered users/index.html.erb within layouts/application (Duration: 3.5ms | Allocations: 1032)
[Webpacker] Everything's up-to-date. Nothing to do
  Rendered layout layouts/application.html.erb (Duration: 11.9ms | Allocations: 4114)
Completed 200 OK in 15ms (Views: 14.0ms | ActiveRecord: 0.1ms | Allocations: 4519)


Started GET "/microposts" for 107.77.219.209 at 2021-03-08 21:23:13 +0000
Cannot render console from 107.77.219.209! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by MicropostsController#index as HTML
  Rendering layout layouts/application.html.erb
  Rendering microposts/index.html.erb within layouts/application
  Micropost Load (0.2ms)  SELECT "microposts".* FROM "microposts"
  ↳ app/views/microposts/index.html.erb:15
  Rendered microposts/index.html.erb within layouts/application (Duration: 21.4ms | Allocations: 3982)
[Webpacker] Everything's up-to-date. Nothing to do
  Rendered layout layouts/application.html.erb (Duration: 38.5ms | Allocations: 7064)
Completed 200 OK in 48ms (Views: 44.2ms | ActiveRecord: 2.1ms | Allocations: 8260)


Started GET "/microposts/new" for 107.77.219.209 at 2021-03-08 21:23:20 +0000
Cannot render console from 107.77.219.209! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by MicropostsController#new as HTML
  Rendering layout layouts/application.html.erb
  Rendering microposts/new.html.erb within layouts/application
  Rendered microposts/_form.html.erb (Duration: 21.2ms | Allocations: 2927)
  Rendered microposts/new.html.erb within layouts/application (Duration: 22.1ms | Allocations: 3292)
[Webpacker] Everything's up-to-date. Nothing to do
  Rendered layout layouts/application.html.erb (Duration: 48.1ms | Allocations: 6375)
Completed 200 OK in 53ms (Views: 50.3ms | ActiveRecord: 0.0ms | Allocations: 6922)


Started GET "/microposts/new" for 107.77.219.209 at 2021-03-08 21:23:33 +0000
Cannot render console from 107.77.219.209! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by MicropostsController#new as HTML
  Rendering layout layouts/application.html.erb
  Rendering microposts/new.html.erb within layouts/application
  Rendered microposts/_form.html.erb (Duration: 2.9ms | Allocations: 688)
  Rendered microposts/new.html.erb within layouts/application (Duration: 3.7ms | Allocations: 797)
[Webpacker] Everything's up-to-date. Nothing to do
  Rendered layout layouts/application.html.erb (Duration: 11.8ms | Allocations: 3876)
Completed 200 OK in 15ms (Views: 14.2ms | ActiveRecord: 0.0ms | Allocations: 4272)


Started POST "/microposts" for 107.77.219.209 at 2021-03-08 21:25:08 +0000
Cannot render console from 107.77.219.209! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by MicropostsController#create as JS
  Parameters: {"authenticity_token"=>"wIc9P9SWFTRYjfPq3rvAXfXgiNchroa3JgUPWBdtl8z/1nyKhKpvCP/7hx2e0RJsas2r+hHFEArn1uLT8Tdbvg==", "micropost"=>{"content"=>"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec.", "user_id"=>"2"}, "commit"=>"Create Micropost"}
  Rendering layout layouts/application.html.erb
  Rendering microposts/new.html.erb within layouts/application
  Rendered microposts/_form.html.erb (Duration: 4.0ms | Allocations: 1769)
  Rendered microposts/new.html.erb within layouts/application (Duration: 6.6ms | Allocations: 1878)
[Webpacker] Everything's up-to-date. Nothing to do
  Rendered layout layouts/application.html.erb (Duration: 13.7ms | Allocations: 4895)
Completed 200 OK in 19ms (Views: 15.7ms | ActiveRecord: 0.0ms | Allocations: 6074)


Started GET "/microposts/new" for 107.77.219.209 at 2021-03-08 21:47:00 +0000
Cannot render console from 107.77.219.209! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by MicropostsController#new as HTML
  Rendering layout layouts/application.html.erb
  Rendering microposts/new.html.erb within layouts/application
  Rendered microposts/_form.html.erb (Duration: 1.4ms | Allocations: 688)
  Rendered microposts/new.html.erb within layouts/application (Duration: 3.1ms | Allocations: 797)
[Webpacker] Everything's up-to-date. Nothing to do
  Rendered layout layouts/application.html.erb (Duration: 10.3ms | Allocations: 3878)
Completed 200 OK in 13ms (Views: 12.7ms | Allocations: 4281)


Started POST "/microposts" for 107.77.219.209 at 2021-03-08 21:47:21 +0000
Cannot render console from 107.77.219.209! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by MicropostsController#create as JS
  Parameters: {"authenticity_token"=>"54yHyZB7szu9XL3lVvPOAhTJbKC4ghs9bJ+PDNCHuk/0+nUX37J1jvrmtamMGMXDu1flt3mWORlUdkRyzLBcCw==", "micropost"=>{"content"=>"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec.", "user_id"=>"2"}, "commit"=>"Create Micropost"}
   (0.1ms)  SELECT sqlite_version(*)
  ↳ app/controllers/microposts_controller.rb:29:in `block in create'
  Rendering layout layouts/application.html.erb
  Rendering microposts/new.html.erb within layouts/application
  Rendered microposts/_form.html.erb (Duration: 2.6ms | Allocations: 1700)
  Rendered microposts/new.html.erb within layouts/application (Duration: 4.3ms | Allocations: 1809)
[Webpacker] Everything's up-to-date. Nothing to do
  Rendered layout layouts/application.html.erb (Duration: 10.9ms | Allocations: 4828)
Completed 200 OK in 18ms (Views: 13.7ms | ActiveRecord: 0.3ms | Allocations: 6466)


Started POST "/microposts" for 107.77.219.209 at 2021-03-08 22:02:23 +0000
Cannot render console from 107.77.219.209! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by MicropostsController#create as JS
  Parameters: {"authenticity_token"=>"54yHyZB7szu9XL3lVvPOAhTJbKC4ghs9bJ+PDNCHuk/0+nUX37J1jvrmtamMGMXDu1flt3mWORlUdkRyzLBcCw==", "micropost"=>{"content"=>"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec.", "user_id"=>"2"}, "commit"=>"Create Micropost"}
   (0.1ms)  SELECT sqlite_version(*)
  ↳ app/controllers/microposts_controller.rb:29:in `block in create'
  Rendering layout layouts/application.html.erb
  Rendering microposts/new.html.erb within layouts/application
  Rendered microposts/_form.html.erb (Duration: 4.1ms | Allocations: 1700)
  Rendered microposts/new.html.erb within layouts/application (Duration: 5.8ms | Allocations: 1809)
[Webpacker] Everything's up-to-date. Nothing to do
  Rendered layout layouts/application.html.erb (Duration: 14.9ms | Allocations: 4826)
Completed 200 OK in 23ms (Views: 17.1ms | ActiveRecord: 0.3ms | Allocations: 6450)


Started GET "/microposts/new" for 107.77.219.209 at 2021-03-08 22:02:28 +0000
Cannot render console from 107.77.219.209! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by MicropostsController#new as HTML
  Rendering layout layouts/application.html.erb
  Rendering microposts/new.html.erb within layouts/application
  Rendered microposts/_form.html.erb (Duration: 1.3ms | Allocations: 688)
  Rendered microposts/new.html.erb within layouts/application (Duration: 3.2ms | Allocations: 797)
[Webpacker] Everything's up-to-date. Nothing to do
  Rendered layout layouts/application.html.erb (Duration: 11.0ms | Allocations: 3876)
Completed 200 OK in 14ms (Views: 13.4ms | ActiveRecord: 0.0ms | Allocations: 4271)


Started POST "/microposts" for 107.77.219.209 at 2021-03-08 22:02:52 +0000
Cannot render console from 107.77.219.209! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by MicropostsController#create as JS
  Parameters: {"authenticity_token"=>"fTPytX67d1aEQCIJA8PCsWwgUrd8XwKjIVWzPeYojTduRQBrMXKx48P6KkXZKMlww77boL1LIIcZvHhD+h9rcw==", "micropost"=>{"content"=>"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec.", "user_id"=>"1"}, "commit"=>"Create Micropost"}
  Rendering layout layouts/application.html.erb
  Rendering microposts/new.html.erb within layouts/application
  Rendered microposts/_form.html.erb (Duration: 4.4ms | Allocations: 1700)
  Rendered microposts/new.html.erb within layouts/application (Duration: 5.9ms | Allocations: 1809)
[Webpacker] Everything's up-to-date. Nothing to do
  Rendered layout layouts/application.html.erb (Duration: 12.9ms | Allocations: 4826)
Completed 200 OK in 18ms (Views: 16.4ms | ActiveRecord: 0.0ms | Allocations: 5841)
  1. 將以下配置添加到 config-->application.rb 並從 _form.html.rb 中刪除 local: true 但 rails 不再顯示錯誤
    module ToyApp
      class Application < Rails::Application
        
        # Fix for errors not showing in browser
        # Stack Overflow suggestion from https://stackoverflow.com/questions/66533418/rails-does-not-render-error-page-when-using-micropost-scaffold
        config.action_view.form_with_generates_remote_forms = false
        # Initialize configuration defaults for originally generated Rails version.
        config.load_defaults 6.0
    
        # Settings in config/environments/* take precedence over those specified here.
        # Application configuration can go into files in config/initializers
        # -- all .rb files in that directory are automatically loaded after loading
        # the framework and any gems in your application.
      end
    end

在帖子的頂部,您說過您添加了這一行:

validates :content, length: { maximum: 140 }

到你的微博 controller。 你的意思是你把它添加到了Micropost model? 如果你說的是你的意思,那就是問題所在。 驗證應添加到Micropost model。

除非

您可能會嘗試的一件事是在您創建Micropost的正下方的 controller 中添加一個byebug

def create
  @micropost = Micropost.new(micropost_params)
  byebug
  respond_to do |format|
    if @micropost.save
      format.html { redirect_to @micropost, notice: 'Micropost was successfully created.' }
      format.json { render :show, status: :created, location: @micropost }
    else
      format.html { render :new }
      format.json { render json: @micropost.errors, status: :unprocessable_entity }
    end
  end
end

當您再次運行代碼時,它將停在該行。 您可以打開運行rails server的終端並檢查:

@micropost.valid?

如果你是真的,那意味着驗證實際上並沒有失敗。 嘗試檢查一下,如果沒有失敗,請嘗試

@micropost.content.length

並確保您所看到的實際上是有意義的。 讓我知道那些東西是做什么的?

如果有錯誤

他們會出現在這里嗎?

@micropost.errors.full_messages

當你在 byebug 中運行它? 此外,檢查new視圖並確保它正確渲染了局部視圖。 這很奇怪,你從生成腳手架中得到了這個。 它應該工作...

澄清

我認為您之前在談論默認錯誤頁面。 驗證錯誤實際上應該顯示在表單上方,與您在提交表單之前看到的視圖相同。 它不是呈現的單獨頁面。 我想也許您是說在提交無效數據后,您已經看到驗證錯誤在表單上方起作用? 如果是這樣,您可以無視這一點。

啊,我想我終於看到了(虛驚)

在顯示錯誤消息的代碼中:

     <ul>
       <% micropost.errors.full_messages.each do |error| %>
         <li><%= error %></li>
       <% end %>
     </ul>
   </div>

現在我想起來,要么應該工作......

<form action="/microposts" accept-charset="UTF-8" data-remote="true" method="post"><input type="hidden" name="authenticity_token" value="54yHyZB7szu9XL3lVvPOAhTJbKC4ghs9bJ+PDNCHuk/0+nUX37J1jvrmtamMGMXDu1flt3mWORlUdkRyzLBcCw==">

你有data-remote="true"那里。 我認為問題在於您之前設置的將默認提交設置為本地的配置:true。 在這種情況下,這不起作用。 我會仔細檢查那部分,看看你是否能看到那里有問題。 否則,您可以將local:true添加到表單標簽:

<%= form_with(model: micropost, local: true) do |form| %>

更新配置

因此,另一個 stackoverflow 帖子建議在config/application.rb中執行此操作

config.action_view.form_with_generates_remote_forms = false

您需要在application.rb而不是development.rb中使用它,因為您的 forms 在開發或生產中應該以相同的方式工作。 確保在進行此更改后重新啟動 rails 服務器以使其生效。

要解決此問題,配置語句:

config.action_view.form_with_generates_remote_forms = false

需要放在最后:

config/application.rb

注意:默認情況下,rails 腳手架將以下內容放在此文件的頂部,最終將反轉之前插入的任何內容:

config.load_defaults 6.0

感謝@dakota-lee-martinez 提供特定於 Rails 的調試技巧,以及在以下位置查找和共享配置選項: data-remote: Stack Overflow post

有關數據遠程的附加信息:true

如果您的初始 Gemfile 包含 rails 版本 6.0 並且您使用 6.1 更改了它,那么更改

config.load_defaults 6.0

config/application.rb

config.load_defaults 6.1

也可以正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM