开发者

Rails: Update score of an user after he wrote a comment

i'm really new to Rails and i'm wondering, how the following could be done:

After an user has written a comment for a sin ( =article), the author ( =user) should get 20 points (for example) added to his score (= user.score). score is a column in my Users table.

My models look like this:

class User < ActiveRecord::Base
  has_many :comments, :dependent => :destroy
  has_many :absolutions, :dependent => :destroy
end

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :sin
end

class Sin < ActiveRecord::Base
  has_many :comments, :dependent => :destroy
end

My comments controller looks like this:

class CommentsController < ApplicationCont开发者_开发知识库roller

  def new
    @comment = Comment.new
  end

  def create
    @sin = Sin.find(params[:sin_id])
    @comment = current_user.comments.build(params[:comment])
    @comment.sin_id = @sin.id
    if @comment.save
      flash[:success] = "Comment created!"
      redirect_to sin_path(@sin)
    else
      flash[:error] = "Comment was not created."
      redirect_to sin_path(@sin)
    end
  end

end

After spending several hours to get this on my own, i'm a little confused. After creating a comment, i would like change a specific value of the associated object User.

What would be the best way to do this?

Thanks for your help!


You could just add it after save :

if @comment.save
  flash[:success] = "Comment created!"
  current_user.score += 20
  current_user.save
  redirect_to sin_path(@sin)
else

BUT, it's always better to do it in your model. So i would create an add_score instance method in your user model and update the score there. Then, i would just call that method in the controller, in the same spot.


Define an after_save callback in your comment model:

class Comment < ActiveRecord::Base
  [...]

  after_save :add_score

  private

  def add_score
    self.user.score += 20
    self.user.save
  end
end


You could use an after_create callback in your comment model that makes the change in the corresponding user?

This kind of logic doesn't belong in the controller.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜