I have three models: Post, Comment, User and Vote.
I’m using polymorphic associations to make posts and comments votable
(users can vote +1 and -1).
Each time the user votes a post or a comment, its id is stored in the user_id foreign key of the vote (and the id of the post and comment should be stored in the votable_id and votable_type foreign keys as well).
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 (omitted the Devise part):
class User < ActiveRecord::Base
has_many :posts, :dependent => :destroy
has_many :comments, :dependent => :destroy
has_many :votes
end
vote.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 (only included relevant parts, omitted stuff like created_at):
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
I have two questions:
- I’m not sure is the
totalshould be a column in thepostsorvotestable. - I know how to create a vote in the terminal (e.g.
Vote.create(polarity => 1). But besides of that, I would like to know how to actually make the Devisecurrent_uservote a post or a comment (in the terminal).
I would appreciate any help in the problems above.
1)
totalcolumn should be in thepoststable.2) There’s no session in the console, you’re not executing any controller or routing code, there’s no
current_user. Instead, just get any user and make him vote.