我应该对 has_many has_many 进行非规范化吗?
我有这样的:
class User < ActiveRecord::Base
has_many :serials
has_many :sites, :through => :series
end
class Serial < ActiveRecord::Base
belongs_to :user
belongs_to :site
has_many :episodes
end
class Site < ActiveRecord::Base
has_many :serials
has_many :users, :through => :serials
end
class Episode < ActiveRecord::Base
belongs_to :serial
end
我想对 User.serials.episodes 进行一些操作,但我知道这意味着各种巧妙的技巧。理论上,我可以将所有剧集数据放入串行(非规范化),然后在需要时按站点分组。
如果我有很多剧集需要查询,这是一个坏主意吗?
谢谢
I have this:
class User < ActiveRecord::Base
has_many :serials
has_many :sites, :through => :series
end
class Serial < ActiveRecord::Base
belongs_to :user
belongs_to :site
has_many :episodes
end
class Site < ActiveRecord::Base
has_many :serials
has_many :users, :through => :serials
end
class Episode < ActiveRecord::Base
belongs_to :serial
end
I would like to do some operations on User.serials.episodes but I know this would mean all sorts of clever tricks. I could in theory just put all the episode data into serial (denormalize) and then group_by Site when needed.
If I have a lot of episodes that I need to query on would this be a bad idea?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不会费心去规范化。
如果您需要查看计数,您可以查看关系上的 counter_cache 以节省查询。
您的外键上有正确的索引吗?如果是这样,从一个额外的连接中提取数据应该不是什么大问题,但您可能需要使用 SQL 来获取一个查询中的所有结果,而无需迭代 .serials:
I wouldn't bother denormalizing.
If you need to look at counts, you can check out counter_cache on the relationship to save querying for that.
Do you have proper indexes on your foreign keys? If so, pulling the data from one extra join shouldn't be that big of a deal, but you might need to drop down to SQL to get all the results in one query without iterating over .serials:
这实际上取决于您需要此应用程序的规模。如果该应用程序不需要为大量的人提供服务,那么就使用它吧。如果您从活动记录关联中获得了很多好处,那么请继续使用它们。随着应用程序的扩展,您可能会发现自己用更直接的方法替换关联使用的特定实例来处理流量负载。
It really depends on the scale you are needing out of this application. If the app isn't going to need to serve tons and tons of people then go for it. If you are getting a lot of benefit from the active record associations then go ahead and use them. As your application scales you may find yourself replacing specific instances of the association use with a more direct approach to handle your traffic load though.