传递轨道关联和神奇计数
在 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 的自动计数来计算它们?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你走在正确的轨道上。但首先你必须解决一个小错误。除非您指示,否则 Rails 不会更新计数器缓存。
将在创建之前和销毁所有关联章节之后自动更新@script.chapter_count。
不幸的是,通过关系处理事情时事情并不那么简单。您将需要通过段落模型中的回调来更新关联脚本的段落计数器。
注意:以下假设您也想在章节中保留段落计数器。
首先将相同的理论应用于章节模型,并将段落计数列应用于脚本表。
现在设置关系:
剩下的就是告诉 Paragraph 将脚本中的段落计数器更新为回调。
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.
不使用缓存的快速而简单的方法是:
The quick and simple way, without using a cache is to do: