2014-02-06 88 views
0

我有兩個模型UserInvestment和一個polymorhic模型Address如何將驗證範圍限定在多態關聯中的特定模型。

class User < ActiveRecord::Base 
    has_one :address, as: :addressable, dependent: :destroy 
    accepts_nested_attributes_for :address 
end 

class Investment < ActiveRecord::Base 
    has_many :addresses, as: :addressable, dependent: :destroy 
    accepts_nested_attributes_for :addresses, reject_if: lambda { |v| v['address'].blank? } && :address_blank, :allow_destroy => true 
end 


class Address < ActiveRecord::Base 
    belongs_to :addressable, polymorphic: true 
    validates :address, presence: true 
end 

現在validates :address, presence: true將同時適用於Investment以及User ,但我希望它僅適用於InvestmentUser。所以我該怎麼做。

謝謝。

回答

0

類投資增加

validates :address_id, presence: true 

和類地址波紋管除去

validates :address, presence: true 
+0

多態,我的投資模式沒有investment_id, –

0
class Address < ActiveRecord::Base 
    belongs_to :addressable, polymorphic: true 
    validates :address, presence: true, if: :investment? 

    protected 

    def investment? 
    addressable_type == 'Investment' 
    end 
end 
+0

我不知道爲什麼,但這是行不通的...我添加了你的修改後,我的投資記錄保存了空白地址, –