In Rails, to automatically count associations, you do:
class Script
has_many :chapters
end
class Chapter
belongs_to :script
end
and you add a chapters_count column into the Script model.
Now, what if you want to count the number of paragraphs in a Script without having a script_id key in the paragraph model ?
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
How do you automatically associate script to paragraph and count them using the automatic count of Rails ?
You're on the right track. But first you've got to address a small error. Rails won't update a counter cache unless you instruct it to.
Will automatically update @script.chapter_count before creation and after destruction of all associated Chapters.
Unfortunately things aren't so simply when dealing :through relationships. You will need to update the associated script's paragraph counter through callbacks in the Paragraph model.
N.B.: The following assumes you want to keep a paragraph counter in Chapter as well.
Start by applying the same theory to the Chapter model, and a paragraphs count column to the Script table.
Now to set up the relationships:
All that's left is to tell Paragraph to update the paragraph counters in script as a callback.