我想创建 Thumbs Up 投票系统,但我不知道如何以最好的方式做到这一点。
这是我的参赛作品#vote(控制器/操作):
def vote
if Entry.where(id: params[:entry_id]).first && Vote.where(entry_id: params[:entry_id], user_id: @current_user.id).first.nil? # Check if entry with given entry_id exist && Check if user vote previously.
Vote.create(entry_id: params[:entry_id], user_id: @current_user.id) # Create vote
ActiveRecord::Base.connection.execute("UPDATE `entries` SET `entries`.`points` = `entries`.`points` + 1 WHERE `entries`.`id` = #{params[:entry_id].to_i}") # Update entry points count.
end
render nothing: true
end
我认为这不是最佳方法,因为此操作有很多查询。这是查询日志:
Started GET "/vote/2" for 127.0.0.1 at 2012-02-20 16:20:01 +0100
Processing by EntriesController#vote as JS
Parameters: {"entry_id"=>"2"}
←[1m←[36mUser Load (1.0ms)←[0m ←[1mSELECT id, name FROM `users` WHERE `users`.`auth_token` = '6f1aa3b944d530a1d52c6f40bcb69398' LIMIT 1←[0m
←[1m←[35mEntry Load (1.0ms)←[0m SELECT `entries`.* FROM `entries` WHERE `entries`.`id` = 2 LIMIT 1
←[1m←[36mVote Load (0.0ms)←[0m ←[1mSELECT `votes`.* FROM `votes` WHERE `votes`.`entry_id` = 2 AND `votes`.`user_id` = 1 LIMIT 1←[0m
←[1m←[35m (0.0ms)←[0m BEGIN
←[1m←[36mSQL (0.0ms)←[0m ←[1mINSERT INTO `votes` (`entry_id`, `user_id`) VALUES (2, 1)←[0m
←[1m←[35m (54.0ms)←[0m COMMIT
←[1m←[36m (16.0ms)←[0m ←[1mUPDATE `entries` SET `entries`.`points` = `entries`.`points` + 1 WHERE `entries`.`id` = 2←[0m
Rendered text template (0.0ms)
Completed 200 OK in 115ms (Views: 1.0ms | ActiveRecord: 78.0ms)
有人知道如何以最好的方式做到这一点吗?