相关疑难解决方法(0)

在一个habtm关系上反缓存?

是否可以在rails 3中的habtm关系上使用计数器缓存?

我真的需要它来加速我的应用程序.

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

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

counter_cache has_many_through sql optimization,减少sql查询次数

我如何优化我的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?

sql optimization activerecord model ruby-on-rails

5
推荐指数
2
解决办法
1341
查看次数

具有多对多关联的模型的计数器缓存

我有一个带有关联的PostTag模型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)

ruby-on-rails

4
推荐指数
2
解决办法
2299
查看次数