我有这种自定义验证方法,它确保你不能对自己的内容投票,它会导致很多 RSpec 测试失败undefined method 'user_id' for nil:NilClass
有没有办法重写自定义验证,或使用本机 Rails 验证?
failing tests
12) Vote votable type
Failure/Error: @vote = FactoryGirl.create(:vote)
NoMethodError:
undefined method `user_id' for nil:NilClass
# ./app/models/vote.rb:18:in `ensure_not_author'
# ./spec/models/vote_spec.rb:5:in `block (2 levels) in <top (required)>'
validate :ensure_not_author
投票.rb
attr_accessible :value, :votable_id, :votable_type
belongs_to :votable, polymorphic: true
belongs_to :user
def ensure_not_author
votable = self.votable_type.downcase
errors.add(:user_id, "You can't vote on your own content.") if self.votable.user_id == self.user_id
end
如果有人需要更多代码,请大喊