views:

50

answers:

1

Right now I have this social media app, where I'm implementing ratings on users per category, What i want to do it's:

Whenever an user casts a vote on an article, it will grab all the votes on the article and make an average of the score/votes and insert that value into another model that i have (User Category Rating), now my question is, Is there some sort of way i can actually make the functions and just call it inside the controller for vote on the create function? Also, what would be the best way to accomplish the average, by pure SQL or is there a "rubyish" way?

If any of you guys need more details, I'll be happy to provide them, thanks for all your help, as always.

EDIT

Right now it inserts the first time, but won't update, perhaps i need another method, this is what i have in the controller right now.

 def create
   @vote = Vote.new(params[:vote])
   @user_rating = UserCategoryRating.new
   @vote.user_id = current_user.id

   @article = Article.find(@vote.article_id)
   @user_rating.category_id = @article.category_id
   @user_rating.user_id = @article.user_id
   @user_rating.rating = @article.votes.average('value')

   if @vote.save
     @user_rating.save
     flash[:notice] = "Your vote has been sumbmitted sucessfully"
     redirect_to :controller => :articles
   else
     flash[:error] = "You have already voted for this article!"
     redirect_to :controller => :articles
  end
end

This it's properly setting the first vote, but after that, is it not updating, perhaps i need to validate that if the votes exist it should update, but how do i accomplish this?

Josh

+2  A: 

You can calculate the average using Active Record calculations:

average(column_name, options = {})

Just call that function during your create action.

sosborn
This works, but there's a small problem, it does not update. I'm going to edit my question, to see the problem.
Gotjosh
If you are only calling this in the create action then yes, it will only happen when you insert new records. If you want it to update after that then you should put this in your "update" method (it should be there if you used scaffolding, otherwise just make a method called update that updates the values you want to update).
sosborn
The real question is, where do i put the condition that if the user already voted on this category updates and if not creates?
Gotjosh
You can test if the object already exists: if Vote.exists?((params[:vote]))
sosborn