donkey
donkey

Reputation: 4363

Validate a polymorphic model's attribute depending on which model it links to in Rails 4

Basically, I have three models: a profileable Profile model, a Staff model and a Client model.

If Profile model is created for Staff, the employee has to be at least 18 years ago. (I use a validates_date helper method to check age, see below) If Profile model is created for Client, then there is no age restriction.

How to achieve this?

Profile.rb:

class Profile < ActiveRecord::Base
  belongs_to :profileable, polymorphic: true
  validates_date        :date_of_birth,    :before => 16.years.ago
end

Staff.rb:

class Staff < ActiveRecord::Base
    has_one :profile, as: :profileable, :dependent => :destroy
end

Client.rb:

class Client < ActiveRecord::Base
    has_one :profile, as: :profileable, :dependent => :destroy
end

Upvotes: 0

Views: 44

Answers (1)

ksarunas
ksarunas

Reputation: 1227

Try using conditional validation

class Profile < ActiveRecord::Base
  STAFF = 'Staff'.freeze

  belongs_to :profileable, polymorphic: true
  validates_date :date_of_birth, before: 18.years.ago, if: staff?

  def staff?
    profileable_type == STAFF
  end
end

Upvotes: 1

Related Questions