在Rails中,要自动计算关联,请执行以下操作:
class Script
has_many :chapters
end
class Chapter
belongs_to :script
end
并在脚本模型中添加了chapters_count列。
现在,如果您想在段落模型中没有script_id键的情况下计算脚本中的段落数量,该怎么办?
class Script
has_many :chapters
has_many :paragraphs # not complete
end
class Chapter
has_many :paragraphs
belongs_to :script
end
class Paragraph
belongs_to :chapter
end
如何自动将脚本与段落关联并使用Rails的自动计数对它们进行计数?
答案 0 :(得分:1)
你走在正确的轨道上。但首先你必须解决一个小错误。除非您指示Rails,否则Rails不会更新计数器缓存。
class Chapter
belongs_to :script, :counter_cache => true
end
在创建之前和销毁所有相关章节之后,将自动更新@ script.chapter_count。
不幸的是,处理时并不是那么简单:通过关系。您需要通过Paragraph模型中的回调更新关联脚本的段落计数器。
N.B。:以下假设你想在章节中保留一个段落计数器。
首先将相同的理论应用于章节模型,并将段落计数列到脚本表。
class PrepareForCounterCache < ActiveRecord::Migration
def self.up
add_column :scripts, :paragraphs_count, :integer, :default => 0
add_column :chapters, :paragraphs_count, :integer, :default => 0
Chapter.reset_column_information
Script.reset_column_information
Chapter.find(:all).each do |c|
paragraphs_count = c.paragraphs.length
Chapter.update_counters c.id, :paragraphs_count => paragraphs_count
Script.update_counters c.script_id, :paragraphs_count => paragraphs_count
end
end
def self.down
remove_column :scripts, :paragraphs_count
remove_column :chapters, :paragraphs_count
end
end
现在建立关系:
class Script
has_many: chapters
has_many: paragraphs, :through => :chapters
end
class Chapter
has_many: paragraphs
belongs_to :script, :counter_cache => true
end
class Paragraph
belongs_to :chapter, :counter_cache => true
end
剩下的就是告诉Paragraph将脚本中的段落计数器更新为回调。
class Paragraph < ActiveRecord::Base
belongs_to :chapter, :counter_cache => true
before_save :increment_script_paragraph_count
after_destroy, :decrement_script_paragraph_count
protected
def increment_script_paragraph_count
Script.update_counters chapter.script_id, :paragaraphs_count => 1
end
def decrement_script_paragraph_count
Script.update_counters chapter.script_id, :paragaraphs_count => -1
end
end
答案 1 :(得分:0)
快速而简单的方法是不使用缓存:
class Script
has_many :chapters
has_many :paragraphs, :through => :chapters
end
script = Script.find(1)
puts script.paragraphs.size #get the count