0

I have a question and answer app that is similar in the way stackoverflow works. The vote model is polymorphic and belongs to 3 other models. A vote is created via a member POST route on each model using a vote method in each controller.

The following user_reputation method which works and sets the user reputation by adding the "second" value of the vote (+5 for up, -3 for down) to the existing user reputation upon creation of a vote, however it feels like bad practice to set the values of the vote like this.

Is there a cleaner/ best practice way to achieve this?

vote.rb

attr_accessible :value, :votable_id, :votable_type
belongs_to :votable, polymorphic: true
belongs_to :user

validates_inclusion_of :value, in: [1, -1]
validates_presence_of :user_id, :value, :votable_id, :votable_type
validates_uniqueness_of :user_id, scope: :votable_id
validates_uniqueness_of :value, scope: :votable_id

after_create :sum_votes

after_create :user_reputation

def user_reputation
    votable = self.votable_type.downcase
    user_rep = self.votable.user
    if self.value == 1
      user_rep.update_attributes(reputation: (user_rep.reputation + 5))
    elsif self.value == -1
      user_rep.update_attributes(reputation: (user_rep.reputation - 3))
    end
  end

vote _form.html.erb

<div class="vote">
    <div id='<%= "#{votes_count}_#{id}" %>' class="vote-box">
        <div class='<%= object.votes_count < 0 ? 'orange-arrows' : 'default-arrows' %>'>
            <h1><%= object.votes_count %></h1>
        </div>
    </div>
    <div id="arrows">
    <%= link_to raw("&#9650;"), vote_path.call(object, value: 1),id: "upvote", remote: true,  method: "post" %><br>
    <%= link_to raw(" &#9660;") , vote_path.call(object, value: -1), id: "downvote", remote: true, method: "post" %>
    </div>
</div>

routes.rb

resources :answers do 
    member { post :vote }
  end

  resources :questions do 
    member { post :vote }
  end 

  resources :comments do 
    member { post :vote }
  end

controller method

def vote 
    @vote = current_user.votes.build(value: params[:value], votable_id: params[:id], votable_type: "Answer")
    respond_to do |format|
    if @vote.save
      format.html { redirect_to :back, notice: "Vote submitted" }
      format.js
    else
      format.html { redirect_to :back, alert: "You can't vote on your own content" }
      format.js
    end
  end
 end

1 Answer 1

1

You can have a look at Active Record Observer. It actually the same as what you are doing, but it lets you separate these logic from your model.

And i don't think you need the first line in the user_reputation method.

1
  • this was cool, has moved off a lot of logic into another class and gave me a chance to refactor nicely as well. Jun 11, 2013 at 22:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.