views:

32

answers:

1

I have a model Vote, and I'm using an after_validation callback.

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

You can see that in my method destroy_reciprocal_votes, I called self.voteable_id and self.voter_id, why does this return nil? and how should I retrieve my id's here?

When I do it in console it works fine:

>> 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  A: 

You don't have to refer to id as long as you specify an association. Try this:

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

Update

Changed to :voteable_id => voteable.

St.Woland
well, It seems I do since that is a the column in the db and it's polymorphic. If I should be able to do so let me know, because that would be a bit cleaner.
Joseph Silvashy
A short example:>> Post.find(:all, :conditions=>{ :user_id => User.find(:first) } )
St.Woland
Well because it is truly a polymorphic model, like the user can cast votes on `features` and they can cast votes on `recipes` so I need to make sure that I'm deleting the proper vote.
Joseph Silvashy
[answered above] Why do you need :voter_type, if you have :voter_id already? @Joseph, can you set up a testing environment and play with this example: Post.delete_all( :user_id => User.find(:first) ) - in application to your case? Should be working fine.
St.Woland
ha, I guess you were right, I did need to call self on it `:voteable_id => self.voteable` but now it is clean and simple.
Joseph Silvashy