开发者

Rails Custom Functions EDIT: Update from inside the controller

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 f开发者_Python百科unctions 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


You can calculate the average using Active Record calculations:

average(column_name, options = {})

Just call that function during your create action.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜