Rails v6.0.0rc1 form_for работает в консоли rails, но не в приложении

Приложение работает в консоли rails в том смысле, что я могу создать действительного пользователя и сохранить его в базе данных, а проверка модели отклоняет пользователя, созданного с недопустимым вводом. Я также могу отображать сообщения об ошибках, используя user.errors.full_messages. Так что в консоли все выглядит нормально. Но когда я повторяю это в приложении в среде разработки, действительный пользователь не сохраняется в базе данных, и я не получаю сообщения об ошибках для недопустимого пользователя.

Это для приложения Rails 6.0.0rc1 с использованием webpacker 4.0.2, postgres 11 и puma 3.12.1. Руби 2.6.3

Это модель пользователя

class User < ApplicationRecord
  before_save { self.email = email.downcase }
  validates :first_name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
  validates :email,      presence: true, length: { maximum: 255 },
                         format: { with: VALID_EMAIL_REGEX },
                         uniqueness: { case_sensitive: false }
  has_secure_password
  validates :password, presence: true, length: { minimum: 6 } 
end

Это контроллер пользователей

class UsersController < ApplicationController

  def show
    @user = User.find(params[:id])
  end

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      flash[:success] = "Welcome to the Option Trader."
      redirect_to @user
    else
      render 'new'
    end
  end

  private

    def user_params
      params.require(:user).permit(:first_name, :email, :password,
                                   :password_confirmation)
    end
end

Это новая страница пользователя (.html.erb)

<div class="container">
  <div class="row">        
    <div class="col-md-6 offset-md-3">
      <form>
        <%= form_for(@user) do |form| %>
          <%= render 'shared/error_messages' %>

          <div class="form-group">  
            <%= form.label :first_name %>
            <%= form.text_field :first_name, class: "form-control" %>
          </div>
          <div class="form-group">
            <%= form.label :email %>
            <%= form.email_field :email, class: "form-control" %>
          </div>
          <div class="form-group">  
            <%= form.label :password %>
            <%= form.password_field :password, class: "form-control", bootstrap: {help: "Must be at least 6 characters long"} %>
          </div>
          <div class="form-group">
            <%= form.label :password_confirmation %>
            <%= form.password_field :password_confirmation, class: "form-control" %>
          </div>
          <div class="text-center">
            <%= form.submit "Create my account", class: "btn btn-primary btn-lg" %>
          </div>      
        <% end %>
      </form>      
    </div>
  </div>
</div>

Я ожидал увидеть сообщения об ошибках, поддерживаемые пользовательской моделью, отображаемые на новой странице пользователей для недопустимых данных и для действительного пользователя, который будет сохранен в базе данных.

Это из development.log:

DEPRECATION WARNING: Single arity template handlers are deprecated. Template handlers must
now accept two parameters, the view object and the source for the view object.
Change:
  >> JbuilderHandler.call(template)
To:
  >> JbuilderHandler.call(template, source)
 (called from <top (required)> at /home/steve/justmoneymatters/optiontrader/config/environment.rb:5)
Started GET "/" for 127.0.0.1 at 2019-05-09 09:38:48 +1000
  [1m[35m (1.3ms)[0m  [1m[34mSELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC[0m
Processing by StaticPagesController#home as HTML
  Rendering static_pages/home.html.erb within layouts/application
  Rendered static_pages/home.html.erb within layouts/application (Duration: 0.9ms | Allocations: 570)
  Rendered layouts/_header.html.erb (Duration: 847.1ms | Allocations: 1457853)
  Rendered layouts/_footer.html.erb (Duration: 0.5ms | Allocations: 260)
Completed 200 OK in 859ms (Views: 853.9ms | ActiveRecord: 0.0ms | Allocations: 1461950)


Started GET "/signup" for 127.0.0.1 at 2019-05-09 09:39:20 +1000
Processing by UsersController#new as HTML
  Rendering users/new.html.erb within layouts/application
  Rendered shared/_error_messages.html.erb (Duration: 0.4ms | Allocations: 206)
  Rendered users/new.html.erb within layouts/application (Duration: 8.3ms | Allocations: 3495)
  Rendered layouts/_header.html.erb (Duration: 0.6ms | Allocations: 718)
  Rendered layouts/_footer.html.erb (Duration: 0.1ms | Allocations: 92)
Completed 200 OK in 24ms (Views: 10.6ms | ActiveRecord: 5.0ms | Allocations: 10945)


Started GET "/signup?authenticity_token=YJylg%2FLP8ffZQJ%2Fsa96tHo9B7aDWNgKQlWkYwcMIiFMtKILokHKTKw60l87VmgUr1pXCw5qzUZTCULU9XxG4CA%3D%3D&user%5Bfirst_name%5D=Stephen&user%5Bemail%5D=stevewill5859%40gmail.com&user%5Bpassword%5D=[FILTERED]&user%5Bpassword_confirmation%5D=[FILTERED]&commit=Create+my+account" for 127.0.0.1 at 2019-05-09 09:39:44 +1000
Processing by UsersController#new as HTML
  Parameters: {"authenticity_token"=>"YJylg/LP8ffZQJ/sa96tHo9B7aDWNgKQlWkYwcMIiFMtKILokHKTKw60l87VmgUr1pXCw5qzUZTCULU9XxG4CA==", "user"=>{"first_name"=>"Stephen", "email"=>"[email protected]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Create my account"}
  Rendering users/new.html.erb within layouts/application
  Rendered shared/_error_messages.html.erb (Duration: 0.1ms | Allocations: 15)
  Rendered users/new.html.erb within layouts/application (Duration: 2.8ms | Allocations: 1071)
  Rendered layouts/_header.html.erb (Duration: 0.8ms | Allocations: 710)
  Rendered layouts/_footer.html.erb (Duration: 0.1ms | Allocations: 89)
Completed 200 OK in 7ms (Views: 5.7ms | ActiveRecord: 0.0ms | Allocations: 3119)

I run server using
foreman start -f Procfile.dev

Procfile.dev file is 

web: bundle exec puma -C config/puma.rb webpacker: ./bin/webpack-dev-server

routes.rb

Rails.application.routes.draw do root 'static_pages#home' get '/subscribe', to: 'static_pages#subscribe' get '/legal', to: 'static_pages#legal' get '/privacy', to: 'static_pages #privacy' get '/about', to: 'static_pages#about' get '/sensitivity', to: 'static_pages#sensitivity' get '/option', to: 'static_pages#option' get '/volatility', to: 'static_pages#volatility' get '/strategy', to: 'static_pages#strategy' get '/signup', to: 'users#new' resources :users end

Thank you for your help so far,  
I have to admit to being confused over
this especially as it works fine in rails
console - I am able to create new users
that are saved to the database and get the
expected error messages when i try to save
an invalid user

    Rails.application.routes.draw do
      root 'static_pages#home'
      get '/subscribe',   to: 'static_pages#subscribe'
      get '/legal',       to: 'static_pages#legal'
      get '/privacy',     to: 'static_pages#privacy'
      get '/about',       to: 'static_pages#about'
      get '/sensitivity', to: 'static_pages#sensitivity'
      get '/option',      to: 'static_pages#option'
      get '/volatility',  to: 'static_pages#volatility'
      get '/strategy',    to: 'static_pages#strategy'
      get '/signup',      to: 'users#new'
      resources :users
    end


I resolved the issue by removing the <form></form> element tags from the users#new view template. I don't know why it worked but it did.

person Steveo00    schedule 08.05.2019    source источник
comment
Вы действительно пробовали смотреть логи?   -  person max    schedule 08.05.2019
comment
Да, но это выглядело нормально. Ниже приведено из development.log:   -  person Steveo00    schedule 09.05.2019
comment
Нет - не выглядит нормально. Это должен быть запрос POST, а не GET, и он выполняет неправильное действие в вашем контроллере. Обычно вы отправляете запрос POST на /users для создания нового ресурса. Маршрут .../new просто отображает форму. Что происходит с вашими маршрутами? guides.rubyonrails.org/routing.html#resources-on-the-web Интернет   -  person max    schedule 09.05.2019