简体   繁体   中英

Rails does not render error page when using micropost scaffold

I am following a Ruby on Rails tutorial but I seem to be hung up on a validation exercise that doesn't render the described error page.

After using the command

rails generate scaffold Micropost content:text user_id:integer

Adding the following validation to the micropost model at apps-->models--micropost.rb

validates :content, length: { maximum: 140 }

The application is supposed to prevent a new message post larger than 140 characters, and throw an error page. Validation part seems to succeed and prevent the message from being saved in the database but the error page doesn't seem to get rendered as verified in the Chrome inspector which only shows the form fields.

These are the steps that I have performed to debug this.

  1. Inspected the page with the Chrome inspector
    results: page seems to be stuck on the form and inputs page, rather than rendering a default rails error page, as described in the tutorial.

  2. Checked the config-->environments-->development.rb file for the following line:

    config.consider_all_requests_local = true

  3. Inspected the microposts controller file which seems to have a branch that should render an error page relevent code looks like this:

    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. Inspected the micropost view that displays the form and validated that it should display an error if it exists.
    view has the following code:

     <%= 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. Reverted back to the original code, deleted the databases and re-followed the steps to validate entering the proper code.

Results were the same. It should also be noted that I have seen other default error pages displayed by rails which leads me to believe that error pages are turned on in this development version of the application.

Using rails version 6.1.3 and the 6th edition of the Ruby on rails tutorial by Micheal Hartl

EDIT: It looks like the app is catching the validation test correctly. The error message that is returned from @micropost.errors.full_messages is what should be displaying on the page. (byebug) @micropost.errors.full_messages ["Content is too long (maximum is 140 characters)"] (byebug) The "new" view looks like what is showing on the page that I was describing as the form page in my original post. (minus the error string)

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

<%= link_to 'Back', microposts_path %>

@dakota-lee-martinez

I just noticed that the code you mentioned is in the form.html.erb file that is created by the scaffolding

  <% 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 %>

This is strange since we can see that the instance value @micropost.errors.full_message is loaded with the error message.

Additional information: I just noticed in the terminal window that rails server is running in, I believe it shows that it has rendered the two pages that we have been talking about.

Here is the 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)

Here is what _form.html.erb is rendering in Chrome inspector elements tab:

    <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>

Full Server logs:

=> 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. Added the config below to config-->application.rb and removed local: true from _form.html.rb but rails is no longer showing the error
    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

At the top of the post you've said that you added this line:

validates :content, length: { maximum: 140 }

to your micropost controller. Did you mean that you added it to the Micropost model? If you said what you meant, that's the problem. The validation should be added to the Micropost model.

Barring That

One thing you might try is to add a byebug into your controller directly below where you created the Micropost .

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

When you run the code again, it will stop at that line. You can open up the terminal running rails server and check this:

@micropost.valid?

If you get true, that means the validation isn't actually failing. Try and check that and if it isn't failing try doing

@micropost.content.length

and make sure that what you're seeing actually makes sense. Let me know what those things do?

If there are errors

Do they show up here?

@micropost.errors.full_messages

When you run that in the byebug? Also, check the new view and make sure it's rendering the partial correctly. This is pretty odd that you're getting this off of generating a scaffold. It should work...

Clarification

I think you were talking about default error pages before. The validation errors should actually show above the form on the same view that you saw before submitting the form. It's not a separate page that is rendered. I think maybe you were saying that you've seen validation errors work before above the form after submitting with invalid data? If so, you can disregard this.

Ah, I think I finally see it (false alarm)

In the code that's displaying the error messages:

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

Now that I think about it, either should work...

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

You've got data-remote="true" there. I think the issue is with that configuration you set up earlier to set the default submit to local: true. That didn't work in this case. I'd double check that part and see if you can see something wrong there. Otherwise, you can just add local:true to the form tag:

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

Update to The Configuration

So, another stackoverflow post is recommending doing this in config/application.rb

config.action_view.form_with_generates_remote_forms = false

You need this in application.rb not development.rb because your forms should work the same way in either development or production. Make sure you restart the rails server after making this change so that it goes into effect.

To resolve this issue, the config statement:

config.action_view.form_with_generates_remote_forms = false

needs to be placed at the end of the:

config/application.rb

NOTE: By default, the rails scaffolding puts the following at the top of this file that ends up reversing anything inserted before it:

config.load_defaults 6.0

Thank you @dakota-lee-martinez for the rails specific debbuging tips, and for finding and sharing the config option at: data-remote: Stack Overflow post

Additional information about data-remote: true

If your initial Gemfile contained rails version 6.0 and you changed it with 6.1 then the changing

config.load_defaults 6.0

in config/application.rb with

config.load_defaults 6.1

also works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM