【发布时间】:2017-07-11 20:56:17
【问题描述】:
我一直在阅读 Rails 教程并被困在第 7 章。问题是在通过 rails 控制台(使用 User.new)将注册信息发布到 rails 后,id、created_at 和 updated_at 都变成了 nil。通过创建用户网页创建用户,电子邮件变为零。
user.rb
class User < ApplicationRecord
before_save { self.email = email.downcase! }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :name, presence: true, length: { maximum: 50 }
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :password, presence: true, length: { minimum: 6 }
has_secure_password
end
users_controller.rb
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
flash[:success] = "Welcome to the Sample App!"
redirect_to @user
else
render 'new'
end
end
def show
@user = User.find(params[:id])
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
end
* new.html.erb *
<% provide(:titel, 'Sign Up') %>
<h1>Sign Up</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for(@user, url: signup_path) do |f| %>
<%= render 'shared/error_messages' %>
<%= f.label :name %>
<%= f.text_field :name, class: "form-control" %>
<%= f.label :email %>
<%= f.email_field :email, class: 'form-control' %>
<%= f.label :password %>
<%= f.password_field :password, class: "form-control" %>
<%= f.label :password_confirmation, "Confirmation" %>
<%= f.password_field :password_confirmation, class: "form-control" %>
<%= f.submit "Create my account", class: "btn btn-primary" %>
<% end %>
</div>
</div>
rails 控制台输出
irb(main):001:0> user = User.new(name: "Test User", email: "test@user.com", password: "secretsecret", password_confirmation: "secretsecret")
=> #<User id: nil, name: "Test User", email: "test@user.com", created_at: nil, updated_at: nil, password_digest: "$2a$10$E1SvEDh.aQSi809sQ7ecReacmSsnxRDUn3IbEawugQD...">
显示第 7 行引发的 /sample_app/app/views/users/show.html.erb:
def gravatar_for(user, size: 100)
gravatar_id = Digest::MD5::hexdigest(user.email.downcase) # this line is highlighted
gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?=#{size}"
image_tag(gravatar_url, alt: user.name, class: "gravatar")
end
通过检查 development.sqlite3,email 字段为 nil。
我哪里错了?谢谢!
Ruby 2.4,Rail 5.1
【问题讨论】:
-
你试过
save吗?User.new(name: "Test User", email: "test@user.com", password: "secretsecret", password_confirmation: "secretsecret").save -
我当然试过了!在 Rails 控制台模式下,它似乎运行良好,但通过 Web 界面电子邮件字段仍然保持为零...
-
只是想知道,你有repo,看看问题出在哪里?
-
repo 好像没有更新。
-
如何将新用户发布到控制器?
标签: ruby-on-rails ruby railstutorial.org