【发布时间】:2014-09-22 12:34:33
【问题描述】:
我正在尝试通过以下方式构建用户注册表单 Michael Hart 的 Rubyonrails 书。 Chapter 7:Singup
但是,我根本无法理解这一小段代码。
def new
@user = User.new
end
我想知道上述代码的目的是什么以及它是如何工作的?
如果我故意排除上述代码(@user=User.new),它会抛出错误消息:
raised: First argument in form cannot contain nil or be empty
如果表单中的第一个参数不能包含 nil 或为空,为什么声明 @user=User.new 会被传递,因为它将 nil 值分配给用户对象。我对 rails 的幼稚理解在这里可能是错误的。
这是完整的代码
控制器/user_controller.rb
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
end
def new
@user = User.new
end
def create
@user = User.new(user_params) # Not the final implementation!
if @user.save
flash[:success] = "Welcome to the Sample App!"
redirect_to @user
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
end
views/users/new.html.erb
<%= f.label :name %> <%= f.text_field :name %> <%= f.label :email %> <%= f.text_field :email %> <%= f.label :password %> <%= f.password_field :password %> <%= f.label :password_confirmation, "Confirmation" %> <%= f.password_field :password_confirmation %> <%= f.submit "Create my account", class: "btn btn-large btn-primary" %> <% end %> </div> </div>
在向受人尊敬的 stackoverflow 社区提出这个问题之前,我在以下链接中寻找答案:-
http://railscasts.com/episodes/250-authentication-from-scratch
First argument in form cannot contain nil or be empty Hartl's Rails 4 Tutorial
感谢您的宝贵时间。
【问题讨论】:
标签: ruby-on-rails-4