Reputation: 71
I'm using one address model with polymorphic.
Class Address < ApplicationRecord
belongs_to :addressable, polymorphic: true, touch: true
...
validates :street_address_1, presence: {with true, message:'cannot be blank'}
validates :street_address_2, presence: {with true, message:'cannot be blank'}
validates :city, presence: {with true, message:'cannot be blank'}
validates :locale, presence: {with true, message:'cannot be blank'}
validates :postal_code, presence: {with true, message:'cannot be blank'}
validates :country, presence: {with true, message:'cannot be blank'}
...
end
Company model
class Company < ApplicationRecord
...
has_many :physical_addresses, :as=> addressable, dependent: :destroy
accepts_nested_attributes_for :physical_addresses, allow_destroy: true
...
end
User model
class User < ApplicationRecord
...
has_many :physical_addresses, :as=> addressable, dependent: :destroy
accepts_nested_attributes_for :physical_addresses, allow_destroy: true
...
end
I'm using the nested attribute for creating or updating the User and Company controller. I'd like to apply the address validation only for User creating and updating. But the companies don't have to be applied the address validation.
Is there any best way to solve this issue?
Upvotes: 0
Views: 268
Reputation: 10079
Write a validator class.
Skip the validations if addressable refers to a Company.
def validate(address)
return unless address.addressable.kind_of?(User)
...
end
Upvotes: 1