我一直在通过Rails教程,并被困在第7章。问题是,通过rails控制台(使用User.new)将注册信息发布到rails后,id,created_at和updated_at变为零。通过创建用户通过creaded用户网页,电子邮件变为零。
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...">
显示/sample_app/app/views/users/show.html.erb第7行引发:
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,电子邮件字段为零。
我哪里错了?谢谢!
Ruby 2.4,Rail 5.1
答案 0 :(得分:0)
User.new
实际上并未向控制器发出请求。它只是在内存中创建User对象的新实例而不将其保存到数据库中。如果你使用User.create
使用相同的参数,你将获得一个id,一个更新的at和一个created_at - 但是这仍然没有向你的控制器发出一个post请求,它只是将它保存到你的数据库中。如果您想对控制器的新操作提出发布请求,您可以使用新的用户表单制作前端并提交,或者您可以使用postman或curl等方式向服务器发出请求。您还必须让您的服务在本地或其他地方运行。我建议在深入研究之前先复习纯红宝石。
答案 1 :(得分:0)
经过很长一段时间寻找错误,这是最终的咳嗽!它上面的主要问题是before_save { self.email = email.downcase! }
代码。在user.rb模型中。before_save { self.email = email.downcase }
,所以,不要强制下载!