rails form_for不提交以创建操作

时间:2015-11-08 19:08:23

标签: ruby-on-rails ruby form-for

我正在尝试设置一个新的用户注册表单,由于某些原因,当我提交表单时,它只是在屏幕上闪烁,而且信息没有打到数据库。我几乎肯定它从未进入create操作,因为我在binding.pry方法的第一行放置了create,服务器从不暂停它。它还会将网址更新为以下内容: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 %>

2 个答案:

答案 0 :(得分:1)

Guarav Gupta的评论是正确的。在视图中将'form'标记更改为'div'标记后,它按预期工作。

答案 1 :(得分:0)

看起来你有路由错误。

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

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