Ruby on Rails: Possible/preferrable to implement single table inheritance after creating separate models?

StackOverflow https://stackoverflow.com/questions/15843971

Вопрос

I've built a simple address book application in my intro Ruby on Rails class with separate models for street addresses (Address), email addresses (Email), and web addresses (Web) using nested forms using a single controller (Entry). I'd like to now change the last two models (Email and Web) to use single table inheritance from a base Url table. Is that preferable (or even possible) compared to rebuilding the app from scratch with the correct inheritance relationships?

I've included my existing models below:

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

How would changing

class Email < ActiveRecord::Base

and

class Web < ActiveRecord::Base

to

class Email < Url

and

class Web < Url

affect my existing application?

Thanks in advance for your help and advice.

Это было полезно?

Решение 2

It is possible to generate a migration that sets up the single table inheritance, but I was unfortunately not able to do this successfully without breaking other things in my app. I went ahead and restarted fresh with a new application and correctly implemented the proper inheritance. This was in the interests of time and the practice of building an application from scratch. In a real-world environment, I'm sure it would be worth investing the time to create the proper migration and changes to the various dependencies.

Thanks Zippie for your advice. I appreciate it.

Другие советы

Be sure to also add the Url class that's inheriting the ActiveRecord::Base class.

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

also add the extra line to your entry.rb:

  has_many :urls, dependent: :destroy
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top