Эта логика контроллера может быть очищена.Если только 1 голос = 1 балл, вы можете использовать counter_cache для отслеживания баллов.Если вам также нужны большие пальцы вниз, вы можете использовать update_counters .
Entry.rb
class Entry < ActiveRecord::Base
has_many :votes
end
Vote.rb
class Vote < ActiveRecord::Base
belongs_to :entry, :counter_cache => :points
belongs_to :user
end
User.rb
class User < ActiveRecord::Base
has_many :votes
end
EntriesController # voice
def vote
Vote.find_or_create_by_entry_id_and_user_id(params[:entry_id], @current_user.id)
render :nothing
end
Для новыхЖурнал голосования SQL:
Vote Load (0.3ms) SELECT "votes".* FROM "votes" WHERE "votes"."entry_id" = 3 AND "votes"."user_id" = 1 LIMIT 1
(0.1ms) BEGIN
SQL (0.4ms) INSERT INTO "votes" ("created_at", "entry_id", "updated_at", "user_id") VALUES ($1, $2, $3, $4) RETURNING "id" [["created_at", Tue, 21 Feb 2012 16:51:54 UTC +00:00], ["entry_id", 3], ["updated_at", Tue, 21 Feb 2012 16:51:54 UTC +00:00], ["user_id", 1]]
Entry Load (0.2ms) SELECT "entries".* FROM "entries" WHERE "entries"."id" = 3 LIMIT 1
SQL (0.2ms) UPDATE "entries" SET "points" = COALESCE("points", 0) + 1 WHERE "entries"."id" = 3
(2.3ms) COMMIT
Для существующего голосования:
Vote Load (0.4ms) SELECT "votes".* FROM "votes" WHERE "votes"."entry_id" = 3 AND "votes"."user_id" = 1 LIMIT 1
=> #<Vote id: 7, user_id: 1, entry_id: 3, created_at: "2012-02-21 16:51:54", updated_at: "2012-02-21 16:51:54">