rails form_for 不提交创建动作

rails form_for does not submit to create action

我正在尝试设置一个新的用户注册表单,但出于某种原因,当我提交该表单时,它只是在屏幕上闪烁,并且信息没有进入数据库。我几乎肯定它永远不会进入 create 操作,因为我在 create 方法的第一行放置了一个 binding.pry 并且服务器从不为此暂停。它还将 url 更新为以下内容:http://localhost:3000/register?utf8=%E2%9C%93&authenticity_token=z%2FZxe...

我假设我遗漏了一些基本的东西,但经过数小时的研究和重构后仍无法弄清楚。这是我的代码:

型号:

class User < ActiveRecord::Base
  has_secure_password validations: false
  validates :username, presence: true, uniqueness: true
  validates :email, presence: true
  validates :password, presence: true, on: :create, length: {minimum: 7}
end

控制器:

class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)

    if @user.save
      session[:user_id] = @user.id
      flash[:notice] = "You have successfully registered."
      redirect_to root_path
    else
      render :new
    end
  end

  private

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

查看:

<%= render 'shared/title', title: 'New User Registration:' %>

<div class='col-lg-6'>
  <div class='well bs-component'>
    <form class='form-horizontal'>
      <legend>Enter New User Details</legend>
      <hr/>
      <%= form_for @user do |f| %>
        <%= render 'shared/error', obj: @user %>
        <div class='form-group'>
          <%= f.label :username, class: 'col-lg-2 control-label' %>
          <div class='col-lg-10'>
            <%= f.text_field :username, class: 'form-control empty', placeholder: 'Username' %>
          </div>
        </div>
        <div class='form-group'>
          <%= f.label :email, class: 'col-lg-2 control-label' %>
          <div class='col-lg-10'>
            <%= f.email_field :email, class: 'form-control empty', placeholder: 'Email' %>
          </div>
        </div>
        <div class='form-group'>
          <%= f.label :password, class: 'col-lg-2 control-label' %>
          <div class='col-lg-10'>
            <%= f.password_field :password, class: 'form-control empty', placeholder: 'Password' %>
          </div>
        </div>
        <%= f.submit @user.new_record? ? "Register" : "Update Profile", class: 'btn btn-primary btn-sm' %> 
      <% end %>
    </div>
  </div>
</div>

路线:

get '/register', to: 'users#new'
resources :users, only: [:show, :create, :edit, :update]

我正在使用 rails v.4.2.4 和 ruby v.2.1.6。任何反馈将不胜感激!谢谢。

更新:

这是根据 Michal 的要求在表单中呈现的部分错误:

<% if obj.errors.any? %>
  <div class="row">
    <div class="alert alert-dismissable alert-danger">
    <button type="button" class="close" data-dismiss="alert">×</button>
      <h5>Oh Snap! The following errors occured:</h5>
      <% obj.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
    </div>
  </div>
<% end %>

您似乎遇到了路由错误。

get '/register', to: 'users#new' 更改为 get '/register, to: 'users#create''

这会将用户保存到数据库中。

Gaurav Gupta 的评论是正确的。一旦我在视图中将 'form' 标记更改为 'div' 标记,它就会按预期工作。