【问题标题】:Weird single table inheritance bug in Ruby on RailsRuby on Rails 中奇怪的单表继承错误
【发布时间】:2015-02-01 14:01:33
【问题描述】:

我今天正在开发一个 Rails 应用程序(Ruby 2.1.3/Rails 4.1),其中有几个类继承自一个类 Item:

主类是Item,有一个继承自Item的Page类和继承自Page类的DownloadPage类。所有对象都存储在一个表中,并通过包含对象类名(Page、Article、DownloadPage 等)的 Type 列进行区分

这里是 UML:

数据库(项目表)中的数据如下所示:

回到问题,当应用程序加载时,我转到 page#index,列出了 Item 表中所有类型为“Page”的对象,一切都很好,但是当应用程序至少使用一次 DownloadPage 类时(例如:DownloadPage.first),page#index 发送所有Page类型的对象加上DownloadPage类型的对象,这是不正常的。

这是一个问题的演示,注意SQL查询第一次(步骤1)只选择Page类型,第二次选择Page+DownloadPage(步骤3):

所以我的问题是,我做错了什么,架构可能是坏的还是别的什么?或者那是一个 rails/ruby 错误

输出:

2.1.3 :001 > Page.first

Page Load (0.9ms)  SELECT  "items".* FROM "items" WHERE "items"."type" IN ('Page')

=> #<Page id: 2, type: "Page",... 

2.1.3 :002 > DownloadPage.first

DownloadPage Load (0.6ms)  SELECT  "items".* FROM "items"  WHERE "items"."type" IN ('DownloadPage') AND "items"."deleted_at" IS NULL  ORDER BY "items"."id" ASC LIMIT 1

=> #<DownloadPage id: 26, type: "DownloadPage",...

2.1.3 :003 > Page.first

Page Load (1.8ms)  SELECT  "items".* FROM "items"  WHERE "items"."type" IN ('Page', 'DownloadPage')

=> #<Page id: 2, type: "Page", title: "sdfPage"...

【问题讨论】:

  • 您的图像不清晰。您可以在这里发布图片中的查询吗?
  • 我更新了 OP,响应格式在 SO 上很奇怪
  • 巨型屏幕截图并不是特别有用。难道没有更简洁的方式来表示这一点吗?
  • 我怀疑这可能与自动加载有关。在 Page.first 的第一次运行中没有加载 DownloadPage 类,而是在第二次运行中。你能确认一下吗?
  • 我用控制台输出更新了帖子,第一个查询选择 Page 类型的项目,第二个命令使用类 DownloadPage,第三个查询与第一个查询完全相同,但返回 Page AND DownloadPage 类型的项目原因

标签: ruby-on-rails ruby inheritance ruby-on-rails-4.1


【解决方案1】:
class Page < Item
end

require_dependency 'download_page'

https://github.com/rails/rails/issues/8699

【讨论】:

  • 感谢这解决了奇怪的行为,但是当我执行 Page.all 时如何防止加载下载页面,例如,我只想要页面而不是两者。
  • 这是预期的行为,因为 DownloadPages 也是 Pages。如果您只想要不是 DownloadPages 的页面,则需要添加 where 子句来限制它
  • 谢谢!我在我的作用域中添加了一堆 where type "Page" 子句并且它起作用了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
  • 1970-01-01
  • 2011-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多