我有一个模型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_id
和self.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)
答案 0 :(得分:1)
只要您指定关联,就不必引用 id 。试试这个:
Vote.delete_all(:vote => false, :voteable_type => "Recipe", :voteable_id => voteable, :voter_type => "User", :voter_id => voter)
<强>更新强>
已更改为:voteable_id =&gt; voteable 强>