У меня есть три модели: Сообщение , Комментарий , Пользователь и Голосование .Я использую полиморфные ассоциации для создания постов и комментариев votable (пользователи могут голосовать за +1 и -1).
Каждый раз, когда пользователь голосует за пост или комментарий, его идентификатор сохраняетсяво внешнем ключе user_id
голосования (а также идентификатор поста и комментария должны быть сохранены во внешних ключах votable_id
и votable_type
).
post.rb:
class Post < ActiveRecord::Base
attr_accessible :title, :content
belongs_to :user
has_many :comments, :dependent => :destroy
has_many :votes, :as => :votable, :dependent => :destroy
end
comment.rb:
class Comment < ActiveRecord::Base
attr_accessible :content, :user_id
belongs_to :post, :counter_cache => true
belongs_to :user
has_many :votes, :as => :votable, :dependent => :destroy
end
user.rb (опущено в части разработки):
class User < ActiveRecord::Base
has_many :posts, :dependent => :destroy
has_many :comments, :dependent => :destroy
has_many :votes
end
voice.rb:
class Vote < ActiveRecord::Base
belongs_to :votable, :polymorphic => true
belongs_to :user
before_create :update_total
protected
// Update the value of total each time a vote is created
def update_total
self.total ||= 0
self.total += self.polarity
end
end
schema.rb (включены только соответствующие части, пропущены такие вещи, как созданный_ат):
create_table "comments", :force => true do |t|
t.text "content"
t.integer "post_id"
t.integer "user_id"
end
add_index "comments", ["post_id", "user_id"], :name => "index_comments_on_micropost_id_and_user_id"
create_table "posts", :force => true do |t|
t.string "content"
t.integer "user_id"
t.string "title"
t.integer "comments_count", :default => 0, :null => false
end
create_table "users", :force => true do |t|
t.string "email", :default => "", :null => false
t.string "username"
end
add_index "users", ["email"], :name => "index_users_on_email", :unique => true
add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true
create_table "votes", :force => true do |t|
t.integer "votable_id"
t.string "votable_type"
t.integer "user_id"
t.integer "polarity" // (+1 or -1)
t.integer "total"
end
У меня есть два вопроса:
- Я не уверен, что
total
должен быть столбцом в таблице posts
или votes
. - Я знаю, как создать голосование в терминале (например,
Vote.create(polarity => 1
).Но кроме этого, я хотел бы знать, как заставить Devise current_user
голосовать за пост или комментарий (в терминале).
Буду признателен за любую помощь в вышеуказанных проблемах.