gpt4 book ai didi

ruby-on-rails - rails form_for 不提交创建操作

转载 作者:太空宇宙 更新时间:2023-11-03 16:20:49 25 4
gpt4 key购买 nike

我正在尝试设置一个新的用户注册表单,但出于某种原因,当我提交该表单时,它只是在屏幕上闪烁,并且信息没有进入数据库。我几乎肯定它永远不会进入 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

Controller :

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

最佳答案

Gaurav Gupta 在评论中是正确的。一旦我在 View 中将“form”标签更改为“div”标签,它就会按预期工作。

关于ruby-on-rails - rails form_for 不提交创建操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33597860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com