Rails 3 - modifying an attribute of other model after model.save

204 views Asked by At

Unfortunately I'm probably still too much a Rails beginner, so, even though I thought about and tried different approaches, I didn't get to work what I want and now have to ask for help again.

I have a REST comment vote mechanism with thumbs up and down for each comment. That works fine, each handled with counter_cache to count. Now, based on these thumbs up and down votes, I want to calculate a plusminus value for each comment, thumbs_up-votes - thumbs_down-votes. Although I'm not sure if it's the most efficient way to deal with that, I am planning to have the plus-minus value as an extra integer attribute of the comment model (whereas the thumbs up and down are own models). So, what I basically want is, that when a thumbs_up is saved, the comment's plusminus attr automatically should be += 1, and respectively for the thumbs_down.save a -= 1.

How can I issue such an action from within the thumbs_up controller? Do I need to modify my form_for or is my approach completely wrong?

Is there an after_save callback to deal with an attribute of a different model?

2

There are 2 answers

12
varatis On BEST ANSWER

From what you've given, it's hard to tell. But I'd say that if you need to show a comment's "thumbs up" and "thumbs down" independently, store them as fields for your Comment model. Then, just making a helper method in your Comment model to get a comment's rating:

   def rating
      thumbs_up - thumbs_down
   end

Edit: With your new comment, I'd still say make a helper method rather than a field.

   #models/comment.rb
   def rating
      thumbs_up.all.length - thumbs_down.all.length #or whatever way you want to do this
   end
0
arieljuod On

if you don't want to mix two different models with helper methods that don't actually belong to neither of those models, you can use Observers http://api.rubyonrails.org/classes/ActiveRecord/Observer.html

your observer will watch one model and do something