活动记录记录无效错误
Posted
技术标签:
【中文标题】活动记录记录无效错误【英文标题】:activerecord recordinvalid error 【发布时间】:2014-08-05 17:56:43 【问题描述】:我正在关注 railscast https://github.com/railscasts/274-remember-me-reset-password/blob/master/auth-after/app/models/user.rb
当我输入我的电子邮件并按发送时,我收到以下错误:
验证失败:密码太短(最少 6 个字符)
指向“保存!”
class User < ActiveRecord::Base
has_many :microposts, dependent: :destroy
has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :followed_users, through: :relationships, source: :followed
has_many :reverse_relationships, foreign_key: "followed_id",
class_name: "Relationship",
dependent: :destroy
has_many :followers, through: :reverse_relationships, source: :follower
has_many :messages
before_save self.email = email.downcase
before_create :create_remember_token
validates :name, presence: true, length: maximum: 50
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
validates :email, presence: true, format: with: VALID_EMAIL_REGEX ,
uniqueness: case_sensitive: false
has_secure_password
validates :password, length: minimum: 6
#TEST
before_create generate_token(:auth_token)
validates_presence_of :password, :on => :create
#before_create :generate_token
def send_password_reset
generate_token(:password_reset_token)
self.password_reset_sent_at = Time.zone.now
save!
#kommer att skicka ett mail till användaren
UserMailer.password_reset(self).deliver
end
def generate_token(column)
begin
self[column] = SecureRandom.urlsafe_base64
end while User.exists?(column => self[column])
end
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.digest(token)
Digest::SHA1.hexdigest(token.to_s)
end
def feed
Micropost.from_users_followed_by(self)
end
def following?(other_user)
relationships.find_by(followed_id: other_user.id)
end
def follow!(other_user)
relationships.create!(followed_id: other_user.id)
end
def unfollow!(other_user)
relationships.find_by(followed_id: other_user.id).destroy
end
private
def create_remember_token
self.remember_token = User.digest(User.new_remember_token)
end
end
【问题讨论】:
显示您的请求和您的控制器。包括强参数和创建方法。 【参考方案1】:这是因为save!
方法在验证失败时引发异常。在您的情况下,它是以下验证:
validates :password, length: minimum: 6
您可能不想在每次保存用户时验证:password
。所以你应该以更聪明的方式编写这个验证,例如:
validates :password, length: minimum: 6 , if: :password_required?
def password_required?
new_record? || password.present?
end
只有当记录是新的或用户想要更改他的密码时,它才会验证密码。
【讨论】:
+1,关于密码验证的评论帮助我解决了一个完全不同的问题。【参考方案2】:这就是帮助我将这一行添加到 development.rb 的原因
Rails.application.routes.default_url_options[:host] = 'localhost:3000'
【讨论】:
以上是关于活动记录记录无效错误的主要内容,如果未能解决你的问题,请参考以下文章
如何解决 Google 的“DKIM 记录格式无效”错误消息?
Firebase Analytics 在应用不活动时错误地记录参与时间
Codeigniter 活动记录类错误与 MySQL 原始查询
EasyMock失败的测试用例“无效使用参数匹配器! 2匹配预期,1记录“错误
如何解决 C++Builder 中的链接器错误“LIBCURL.LIB 包含无效的 OMF 记录,类型 0x21(可能是 COFF)”?