对于在发现者中调用“自我”感到困惑

时间:2010-01-17 01:10:01

标签: ruby-on-rails

我有一个模型Vote,我正在使用after_validation回调。

class Vote < ActiveRecord::Base

  after_validation :destroy_reciprocal_votes

  belongs_to :voteable, :polymorphic => true
  belongs_to :voter, :polymorphic => true

  private

  def destroy_reciprocal_votes
    votes = Vote.delete_all(:vote => false, :voteable_type => "Recipe", :voteable_id => self.voteable_id, :voter_type => "User", :voter_id => self.voter_id)
  end
end

您可以在我的方法destroy_reciprocal_votes中看到,我调用了self.voteable_idself.voter_id,为什么会返回nil?我应该如何在这里找回我的身份?

当我在控制台中执行此操作时,它可以正常工作:

>> voteable_id = "3"
>> voter_id = "162"
>> Vote.delete_all(:vote => false, :voteable_type => "Recipe", :voteable_id => voteable_id, :voter_type => "User", :voter_id => voter_id)

1 个答案:

答案 0 :(得分:1)

只要您指定关联,就不必引用 id 。试试这个:

Vote.delete_all(:vote => false, :voteable_type => "Recipe", :voteable_id => voteable, :voter_type => "User", :voter_id => voter)

<强>更新

已更改为:voteable_id =&gt; voteable