在Rails中关联Post,Comment,User和Vote模型的有效方法是什么?
现在,我有三个模型Post,Comment和User(使用Devise )关联如下:
post.rb:
class Post true, :length => { :maximum => 30 }, :uniqueness => true validates :content, :presence => true, :uniqueness => true belongs_to :user has_many :comments, :dependent => :destroy end
comment.rb:
class Comment true belongs_to :user end
user.rb:
class User :destroy has_many :comments, :dependent => :destroy def self.find_for_facebook_oauth(access_token, signed_in_resource=nil) data = access_token.extra.raw_info if user = User.where(:email => data.email).first user else # Create a user with a stub password. User.create!(:email => data.email, :password => Devise.friendly_token[0,20]) end end end
我想添加一个名为Vote的第四个模型,其中包含以下条件:
- post和评论都可以投票(上下)并显示总数/总和。
- 每个post都会有很多票数(上下)并显示总票数/总和。
- 每条评论都会有很多票
- 每次投票时都应存储用户的ID,这样我就可以限制每个用户一票,并显示投票用户的ID /名称(不确定在哪里存储)
现在,我不确定这是否是使用多态关联和/或计数器缓存的好机会。
什么是关联这些post,评论,用户和投票模型的有效方式? (如果可能的话,我想看看迁移的样子)
这是多态关联有用的完美教科书示例。
您的votes
表迁移将如下所示:
create_table :votes do |t| t.references :votable, :polymorphic => true t.references :user t.integer :polarity t.integer :total end
这将创建一个具有此架构的表:
id INTEGER votable_id INTEGER votable_type VARCHAR user_id INTEGER polarity INTEGER total INTEGER
在这里, user_id
将是投票的人,对于upvote, polarity
将是’1’或对于downvote, polarity
将是’-1’(这可以让你只需求极性来获得upvotes和downvotes来取消), votable_type
将包含投票的内容( Post
或Comment
), votable_id
将包含votable_id
用事物的ID, total
投票total
将保留投票总额(效率)。
然后你的模型看起来像这样:
class Vote < ActiveRecord::Base belongs_to :votable, :polymorphic => true belongs_to :user before_create :update_total protected def update_total self.total ||= 0 self.total += self.polarity end end class Post < ActiveRecord::Base has_many :votes, :as => :votable end class Comment < ActiveRecord::Base has_many :votes, :as => :votable end class User < ActiveRecord::Base has_many :votes end