2016-04-14 7 views
0

基本的に、プロファイル可能なProfileモデル、Staffモデル、Clientモデルの3つのモデルがあります。Rails 4でリンクするモデルに応じて多態性モデルの属性を検証します。

ProfileモデルがStaff用に作成されている場合、従業員は少な​​くとも18年前でなければなりません。 (validates_dateヘルパーメソッドを使用して年齢を確認します。以下を参照してください) モデルがClient用に作成されている場合、年齢制限はありません。

これを行うには?

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 

答えて

1

は、条件付きの検証を使用してみてください

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 
関連する問題