简体   繁体   English

ActiveRecord为与has_and_belongs_to_many的MySQL关系生成昂贵的DESCRIBE查询

[英]ActiveRecord generates expensive DESCRIBE-queries for has_and_belongs_to_many relation with MySQL

We have a Rails3 app we've just started development on. 我们有一个Rails3应用程序,我们刚刚开始开发。 We use a has_and_belongs_to_many relation between two models. 我们在两个模型之间使用has_and_belongs_to_many关系。 Every time we use one of these models, ActiveRecord executes a DESCRIBE-query on the join-table, eg: 每次我们使用其中一个模型时,ActiveRecord都会在连接表上执行DESCRIBE查询,例如:

SQL (1.1ms)  describe `articles_tags`

These queries are relatively expensive (that is, more than 10 times slower than the actual SELECT-query) and are executed very often. 这些查询相对昂贵(即,比实际的SELECT查询慢10倍以上)并且经常执行。 They don't seem necessary to me: the table was automatically generated because of the has_and_belongs_to_many-relation so ActiveRecord should already be aware of its structure (just an article_id and a tag_id column). 它们对我来说似乎没有必要:由于has_and_belongs_to_many-relation,表格是自动生成的,因此ActiveRecord应该已经知道它的结构(只是一个article_id和一个tag_id列)。

Is there a good reason for this behaviour? 这种行为有充分的理由吗? If not, how do I stop it from happening? 如果没有,我该如何阻止它发生?

In development mode, the server constantly recreates all the classes so you don't have to restart the server for every change. 在开发模式下,服务器会不断重新创建所有类,因此您无需为每次更改重新启动服务器。 In production, your models will be cached and it shouldn't need to describe the tables constantly. 在生产中,您的模型将被缓存,不应该不断地描述表格。 In your development.rb file, you'll see this line: 在您的development.rb文件中,您将看到以下行:

config.cache_classes = false

Which drives this behavior. 这推动了这种行为。 It should be set to true in production.rb 它应该在production.rb中设置为true

If your table doesn't have a primary key it will run describe on each query. 如果您的表没有主键,它将在每个查询上运行describe。 I fixed mine adding a primary key. 我修复了我添加主键的问题。 Works even in dev mode. 即使在开发模式下也能工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM