【问题标题】:Ruby on Rails: Possible/preferrable to implement single table inheritance after creating separate models?Ruby on Rails:在创建单独的模型后可能/最好实现单表继承?
【发布时间】:2013-05-24 05:01:11
【问题描述】:

我在我的 Ruby on Rails 简介类中构建了一个简单的地址簿应用程序,它使用单个控制器(条目)使用嵌套表单为街道地址(地址)、电子邮件地址(电子邮件)和网址(Web)提供了单独的模型)。我现在想更改最后两个模型(电子邮件和 Web)以使用来自基本 Url 表的单表继承。与使用正确的继承关系从头开始重建应用程序相比,这是否更可取(甚至可能)?

我在下面包含了我现有的模型:

class Entry < ActiveRecord::Base
  attr_accessible :first_name, :last_name, :addresses_attributes, :webs_attributes, :emails_attributes
  has_many :addresses, dependent: :destroy
  has_many :emails, dependent: :destroy
  has_many :webs, dependent: :destroy
  accepts_nested_attributes_for :addresses, :emails, :webs, allow_destroy: true, reject_if: :all_blank
end

class Address < ActiveRecord::Base
  belongs_to :entry
  belongs_to :address_type
  attr_accessible :address_type_id, :city, :state, :street, :zip
end

class Email < ActiveRecord::Base
  belongs_to :entry
  belongs_to :address_type
  attr_accessible :address_type_id, :email, :entry_id
  validates_email_format_of :email
end

class Web < ActiveRecord::Base
  belongs_to :entry
  belongs_to :address_type
  attr_accessible :address_type_id, :web, :entry_id
end

如何改变

class Email < ActiveRecord::Base

class Web < ActiveRecord::Base

class Email < Url

class Web < Url

影响我现有的应用程序?

提前感谢您的帮助和建议。

【问题讨论】:

    标签: ruby-on-rails refactoring single-table-inheritance


    【解决方案1】:

    请务必添加继承 ActiveRecord::Base 类的 Url 类。

    class Url < ActiveRecord::Base
      belongs_to :entry
      belongs_to :address_type
      attr_accessible :address_type_id :entry_id
    end
    
    class Email < Url
      attr_accessible :email
      validates_email_format_of :email
    end
    
    class Web < Url
      attr_accessible :web
    end
    

    还将额外的行添加到您的 entry.rb:

      has_many :urls, dependent: :destroy
    

    【讨论】:

      【解决方案2】:

      可以生成一个设置单表继承的迁移,但不幸的是,如果不破坏我的应用程序中的其他内容,我无法成功地做到这一点。我继续使用新应用程序重新启动并正确实现了正确的继承。这符合时间和从头构建应用程序的实践。在现实世界的环境中,我相信花时间创建适当的迁移和对各种依赖项的更改是值得的。

      感谢 Zippie 的建议。我很感激。

      【讨论】:

        猜你喜欢
        • 2013-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-01
        • 1970-01-01
        相关资源
        最近更新 更多