是否可以在rails 3中的habtm关系上使用计数器缓存?
我真的需要它来加速我的应用程序.
我如何优化我的SQL查询,忽略这样的情况:
Meeting.find(5).users.size => SELECT COUNT(*)FROM ... WHERE ...
User.find(123).meetings.size => SELECT COUNT(*)FROm ... WHERE ...
我不知道如何在这里使用counter_cache.
这是我的模型关系:
class Meeting < ActiveRecord::Base
has_many :meeting_users
has_many :users, :through => meeting_users
end
class User < ActiveRecord::Base
has_many :meeting_users
has_many :meetings, :through => meeting_users
end
class Meeting_user < ActiveRecord::Base
belongs_to :meeting
belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)
什么是最优解决方案?
如何在这里实现counter_cache?
我有一个带有关联的Post和Tag模型many-to-many:
post.rb:
class Post < ActiveRecord::Base
attr_accessible :title, :content, :tag_names
has_many :taggings, :dependent => :destroy
has_many :tags, :through => :taggings
attr_writer :tag_names
after_save :assign_tags
def tag_names
@tag_names || tags.map(&:name).join(" ")
end
private
def assign_tags
ntags = []
@tag_names.to_s.split(" ").each do |name|
ntags << Tag.find_or_create_by_name(name)
end
self.tags = ntags
end
end
Run Code Online (Sandbox Code Playgroud)
tag.rb:
class Tag < ActiveRecord::Base
has_many :taggings, :dependent => :destroy
has_many :posts, :through => :taggings
has_many :subscriptions
has_many :subscribed_users, :source => :user, :through => …Run Code Online (Sandbox Code Playgroud)