我有三种模式:发布,评论,用户和投票。 我正在使用多态关联来发布帖子和评论可投票 (用户可以投票+1和-1)。
每次用户投票或评论时,其ID都存储在投票的user_id
外键中(帖子和评论的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
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(仅包含相关部分,省略了像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
我有两个问题:
total
应该是posts
或votes
表中的列。Vote.create(polarity => 1
)。但除此之外,我想知道如何让Devise current_user
投票或发表评论(在终端中)。我很感激上述问题的任何帮助。
答案 0 :(得分:0)
1)total
列应位于posts
表中。
2)控制台中没有会话,你没有执行任何控制器或路由代码,没有current_user
。相反,只是让任何用户并让他投票。
u = User.first
p = Post.first
Vote.create(votable: p, user: u)