added post voting

This commit is contained in:
albert
2010-02-15 17:45:09 -05:00
parent 80f033f253
commit 9f353c32f4
10 changed files with 112 additions and 19 deletions

View File

@@ -1,6 +1,4 @@
class Comment < ActiveRecord::Base
class VotingError < Exception ; end
class Comment < ActiveRecord::Base
validates_format_of :body, :with => /\S/, :message => 'has no content'
belongs_to :post
belongs_to :creator, :class_name => "User"
@@ -35,7 +33,7 @@ class Comment < ActiveRecord::Base
votes.create(:user_id => user.id)
else
raise VotingError.new("You have already voted for this comment")
raise CommentVote::Error.new("You have already voted for this comment")
end
end
end

View File

@@ -1,4 +1,6 @@
class CommentVote < ActiveRecord::Base
class Error < Exception ; end
belongs_to :comment
belongs_to :user

View File

@@ -12,6 +12,7 @@ class Post < ActiveRecord::Base
has_one :unapproval, :dependent => :destroy
has_one :upload, :dependent => :destroy
has_many :versions, :class_name => "PostVersion", :dependent => :destroy
has_many :votes, :class_name => "PostVote", :dependent => :destroy
attr_accessible :source, :rating, :tag_string, :old_tag_string
module FileMethods
@@ -140,7 +141,7 @@ class Post < ActiveRecord::Base
self.source = version.source
self.rating = version.rating
self.tag_string = version.tag_string
save
save!
end
end
@@ -473,6 +474,26 @@ class Post < ActiveRecord::Base
end
end
module VoteMethods
def can_be_voted_by?(user)
!votes.exists?(["user_id = ?", user.id])
end
def vote!(user, is_positive)
if can_be_voted_by?(user)
if is_positive
increment!(:score)
else
decrement!(:score)
end
votes.create(:user_id => user.id)
else
raise PostVote::Error.new("You have already voted for this comment")
end
end
end
include FileMethods
include ImageMethods
include ModerationMethods
@@ -483,6 +504,7 @@ class Post < ActiveRecord::Base
include UploaderMethods
include PoolMethods
extend SearchMethods
include VoteMethods
def reload(options = nil)
super

5
app/models/post_vote.rb Normal file
View File

@@ -0,0 +1,5 @@
class PostVote < ActiveRecord::Base
class Error < Exception ; end
belongs_to :post
end

View File

@@ -14,10 +14,6 @@ class User < ActiveRecord::Base
after_save :update_cache
scope :named, lambda {|name| where(["lower(name) = ?", name])}
def can_update?(object, foreign_key = :user_id)
is_moderator? || is_admin? || object.__send__(foreign_key) == id
end
module NameMethods
module ClassMethods
def find_name(user_id)
@@ -100,5 +96,9 @@ class User < ActiveRecord::Base
include PasswordMethods
extend AuthenticationMethods
include FavoriteMethods
def can_update?(object, foreign_key = :user_id)
is_moderator? || is_admin? || object.__send__(foreign_key) == id
end
end