小编Syn*_*zia的帖子

多态关系和计数器缓存

所以我有一个应用程序有2个不同的模型,评论和回复,每个你可以同意或不同意,所以我有一个名为Emotion的多态模型.这是我的代码:

class Comment < ActiveRecord::Base
  belongs_to :user
  has_many :replies
  has_many :emotions, :as => :emotionable
end



class Reply < ActiveRecord::Base
  belongs_to :user
  belongs_to :comment
  has_many :emotions, :as => :emotionable
end

class Emotion < ActiveRecord::Base
  belongs_to :emotionable, :polymorphic => :true  
end
Run Code Online (Sandbox Code Playgroud)

所以这一切都很好,但是我需要为Comment和Reply添加一个计数器缓存,以便获得每个对象的Agrees和Disagree的大小.在所有文档中,它都有使用正常多态关联进行计数器缓存的示例,而不是具有额外条件的计数缓存.作为参考,Emotion的模式如下所示:

create_table "emotions", :force => true do |t|
  t.integer  "user_id"
  t.string   "emotion"
  t.integer  "emotionable_id"
  t.string   "emotionable_type"
  t.datetime "created_at",       :null => false
  t.datetime "updated_at",       :null => false
end
Run Code Online (Sandbox Code Playgroud)

TL:DR - 我需要能够通过计数器缓存对多态关联调用@commet.agrees_count,@ comment.disagrees_count,@ reply.agrees_count和@ reply.disagrees_count.所以评论和回复将需要2个计数器缓存.

ruby-on-rails polymorphic-associations ruby-on-rails-3

9
推荐指数
3
解决办法
4681
查看次数

使用日期时,我可以用零值做什么?

所以我的数据库中有一个带有日期字段的对象,除了有时它将是零.在视图中是否有一种方法可以将其显示为字符串值.可能像TBA之类的东西?

ruby-on-rails ruby-on-rails-3

1
推荐指数
1
解决办法
44
查看次数