2011-08-29 57 views
4

我的用户模型中有一个validates_confirmation_of :password。问题是我也运行@comment.user.save!当创建评论来更新用户帐户的一些属性。Rails仅在用户创建或更新时验证

创建评论Validation failed: Password confirmation can't be blank时出现错误。我无法将:on => "save"添加到我的验证中,因为我的comments控制器也在调用保存功能。

我已阅读此主题Rails model validation on create and update only,但它不回答我的具体问题。

UPDATE 用户模型片段:

class User < ActiveRecord::Base 

    attr_accessor :password 

    # validations 
    validates_presence_of :username 
    validates_length_of :username, :within => 6..25 
    validates_uniqueness_of :username 
    validates_presence_of :email 
    validates_length_of :email, :maximum => 100 
    validates_format_of :email, :with => EMAIL_REGEX 
    validates_confirmation_of :password, :if => :password_changed? 
    validates_presence_of :password_confirmation 
    validates_length_of :password, :within => 4..25, :on => :create 

    before_save :create_hashed_password 
    after_save :clear_password 

    private 

    def clear_password 
    self.password = nil 
    end 

end 

回答

6

根据此validates_confirmation_of如果password_confirmation字段为零,则该模型应该是有效的。你把它存储到DDBB?或者你的验证可能有问题,你可以在这里粘贴你的用户模型吗?

无论哪种方式,你可以尝试这样的:

validates_presence_of :password_confirmation, if: -> { password.present? } 
validates_confirmation_of :password, if: -> { password.present? } 
+0

也许它失败的原因是因为我有'validates_presence_of:password_confirmation'?我补充说,因为如果用户将其留空,它不会检查它。另外,它说':password_changed?'是未定义的。我需要定义这个吗? –

+0

由于密码是虚拟字段,因此密码方法password_changed?没有生成。我编辑我的答案来纠正这个问题,它应该工作。 – cicloon

+0

非常感谢。这正是我所错过的。 –

6

为什么你到底跑@comment.user.save!?触摸(例如更新时间戳)和增加评论计数可以通过内置机制完成。


编辑: 我建议类似于:这种方法的

class Comment < ActiveRecord::Base 
    after_save :rank_user 

    def rank_user 
    # calculate rank 
    user.update_attribute(:rank, rank) 
    end 
end 

优点:

  1. 你的控制器和模型将是干净rank_user将被称为自动,没有明确的电话@comment.user.save!
  2. 根据update_attribute documentation,验证将被跳过,然后导致没有密码确认错误。
+0

我正在运行,因为我更新user.rank属性。我可以在我的评论控制器之外做些什么吗? –

+0

增加了一个解决方案。希望这会对你有用! –

相关问题