Возможно, вам следует использовать полиморфную ассоциацию.
Итак, Common
(плохое имя, IMO) может выглядеть следующим образом:
# == Schema Information
#
# Table name: commons
#
# id :integer not null, primary key
# commonable_id :integer
# commonable_type :string
# ... other stuff ...
# created_at :datetime not null
# updated_at :datetime not null
#
class Common < ApplicationRecord
belongs_to :commonable, polymorphic: true
... other stuff ...
end
Обратите внимание, что у вас будет commonable_type
и commonable_id
, что позволяетполиморфизм.
Тогда Band
может выглядеть так:
class Band < ApplicationRecord
has_one :common, as: :commonable
... other stuff ...
end
Аналогично, Venue
может выглядеть так:
class Venue < ApplicationRecord
has_one :common, as: :commonable
... other stuff ...
end
Что позволит вам сделать:
@venue.common
@band.common
Кстати, Common
выглядит как смесь по крайней мере пары классов-кандидатов, а именно PhysicalAddress
и PhoneNumber
.
Итак, у вас может быть что-то вроде:
# == Schema Information
#
# Table name: phone_numbers
#
# id :integer not null, primary key
# phoneable_id :integer
# phoneable_type :string
# number :string
# note :string
# created_at :datetime not null
# updated_at :datetime not null
#
class PhoneNumber < ApplicationRecord
belongs_to :phoneable, polymorphic: true
end
И
# == Schema Information
#
# Table name: physical_addresses
#
# id :integer not null, primary key
# physical_addressable_id :integer
# physical_addressable_type :string
# address1 :string
# address2 :string
# city :string
# state :string
# zip :string
# created_at :datetime not null
# updated_at :datetime not null
#
class PhysicalAddress < ApplicationRecord
belongs_to :physical_addressable, polymorphic: true
end
А затем выполните:
class Band < ApplicationRecord
has_one :common, as: :commonable
has_one :physical_address, as: :physical_addressable
has_one :phone1, as: :phoneable, class_name: 'PhoneNumber'
has_one :phone2, as: :phoneable, class_name: 'PhoneNumber'
end
Вам понадобитсячто class_name
, поскольку rails не сможет вывести имя класса (PhoneNumber
) из имени ассоциации (phone1
и phone2
).