Validate方法看不到依赖项

时间:2016-08-10 11:46:10

标签: ruby-on-rails

我想在投票资源上进行自定义验证

class Vote < ActiveRecord::Base

  include HasUser  
  belongs_to :votable, polymorphic: true   

  validates :votable, :vote_field, presence: true 
  validates :user_id, uniqueness: { scope: [:votable_id, :votable_type] } 
  validate :vote_permission

  def vote_permission
    errors.add(:permission, 'denied') if self.vote_permitted?
  end

  def vote_permitted?
    self.user == self.votable.user   
  end  

  def down?
   self.vote_field == -1 
  end

  def up?
    self.vote_field == 1 
  end
end

在我的规格中,我收到了错误 投票应验证:user_id不能为空/假      失败/错误:self.user == self.votable.user 哪里错了?我应该怎么做才能使这项工作?

这有帮助

  def vote_permitted?
    if votable.present?
      self.user == self.votable.user 
    else
     false
    end  
  end

但这是一个正确的设计吗?对不起我的英文

0 个答案:

没有答案