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