Update post votes after save post_vote

This commit is contained in:
Rei
2014-01-14 21:25:12 +08:00
parent 43b797297e
commit a16c9885b2
5 changed files with 37 additions and 6 deletions

View File

@@ -4,4 +4,12 @@ class PostVote < ActiveRecord::Base
enum value: { down: -1, up: 1 }
validates :value, presence: true
after_save :update_post_votes
def update_post_votes
if value_changed?
post.increment! :votes, VALUE[value]
end
end
end

View File

@@ -1,8 +1,8 @@
class CreateTopics < ActiveRecord::Migration
def change
create_table :topics do |t|
t.string :title
t.references :user, index: true
t.string :title
t.timestamps
end

View File

@@ -1,10 +1,11 @@
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.text :content
t.integer :post_number
t.references :topic, index: true
t.references :user, index: true
t.text :content
t.integer :post_number
t.integer :votes, default: 0
t.timestamps
end

View File

@@ -29,10 +29,11 @@ ActiveRecord::Schema.define(version: 20140114124558) do
add_index "post_votes", ["user_id"], name: "index_post_votes_on_user_id", using: :btree
create_table "posts", force: true do |t|
t.text "content"
t.integer "post_number"
t.integer "topic_id"
t.integer "user_id"
t.text "content"
t.integer "post_number"
t.integer "votes", default: 0
t.datetime "created_at"
t.datetime "updated_at"
end
@@ -41,8 +42,8 @@ ActiveRecord::Schema.define(version: 20140114124558) do
add_index "posts", ["user_id"], name: "index_posts_on_user_id", using: :btree
create_table "topics", force: true do |t|
t.string "title"
t.integer "user_id"
t.string "title"
t.datetime "created_at"
t.datetime "updated_at"
end

View File

@@ -7,4 +7,25 @@ class PostVoteTest < ActiveSupport::TestCase
assert_equal 'up', vote.value
assert vote.up?
end
test "should inc post votes" do
post = create(:post)
assert_equal 0, post.votes
create(:post_vote, post: post, value: 'up')
assert_equal 1, post.votes
create(:post_vote, post: post, value: 'down')
assert_equal 0, post.votes
end
test "should inc post votes after vote update" do
post = create(:post)
vote = create(:post_vote, post: post, value: 'up')
assert_equal 1, post.votes
vote.update_attribute :value, 'down'
assert_equal 0, post.votes
end
end