75 lines
2.5 KiB
Ruby
75 lines
2.5 KiB
Ruby
class Subproject < ApplicationRecord
|
|
belongs_to :project
|
|
has_one :subproject_address, dependent: :destroy
|
|
|
|
belongs_to :client, class_name: 'Client', optional: true
|
|
belongs_to :owner, class_name: 'Client', optional: true
|
|
belongs_to :builder, class_name: 'Client', optional: true
|
|
|
|
accepts_nested_attributes_for :client, reject_if: ->(attrs) { attrs['id'].present? || attrs.values.all?(&:blank?) }
|
|
accepts_nested_attributes_for :owner, reject_if: ->(attrs) { attrs['id'].present? || attrs.values.all?(&:blank?) }
|
|
accepts_nested_attributes_for :builder, reject_if: ->(attrs) { attrs['id'].present? || attrs.values.all?(&:blank?) }
|
|
accepts_nested_attributes_for :subproject_address, allow_destroy: true, reject_if: ->(attrs) { attrs['id'].present? || attrs.values.all?(&:blank?) }
|
|
|
|
|
|
validates :subproject_name, presence: true
|
|
validate :client_presence_check
|
|
validate :owner_presence_check
|
|
validate :builder_presence_check
|
|
|
|
validates_associated :client, :owner, :builder
|
|
|
|
def client_attributes=(attributes)
|
|
return if self.client_id.present?
|
|
self.client = Client.find_or_initialize_by(email: attributes[:email])
|
|
self.client.assign_attributes(attributes)
|
|
end
|
|
|
|
def owner_attributes=(attributes)
|
|
return if self.owner_id.present?
|
|
self.owner = Client.find_or_initialize_by(email: attributes[:email])
|
|
self.owner.assign_attributes(attributes)
|
|
end
|
|
|
|
def builder_attributes=(attributes)
|
|
return if self.builder_id.present?
|
|
self.builder = Client.find_or_initialize_by(email: attributes[:email])
|
|
self.builder.assign_attributes(attributes)
|
|
end
|
|
|
|
private
|
|
|
|
def client_presence_check
|
|
if client_id.blank? && (client_attributes_blank?)
|
|
errors.add(:client, "must be selected or a new client must be provided")
|
|
end
|
|
end
|
|
|
|
def owner_presence_check
|
|
if owner_id.blank? && (owner_attributes_blank?)
|
|
errors.add(:owner, "must be selected or a new owner must be provided")
|
|
end
|
|
end
|
|
|
|
def builder_presence_check
|
|
if builder_id.blank? && (builder_attributes_blank?)
|
|
errors.add(:builder, "must be selected or a new builder must be provided")
|
|
end
|
|
end
|
|
|
|
def client_attributes_blank?
|
|
return true if client.nil?
|
|
client.attributes.except("id", "created_at", "updated_at").values.all?(&:blank?)
|
|
end
|
|
|
|
def owner_attributes_blank?
|
|
return true if owner.nil?
|
|
owner.attributes.except("id", "created_at", "updated_at").values.all?(&:blank?)
|
|
end
|
|
|
|
def builder_attributes_blank?
|
|
return true if builder.nil?
|
|
builder.attributes.except("id", "created_at", "updated_at").values.all?(&:blank?)
|
|
end
|
|
|
|
end |