2014-02-06 80 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

我不知道为什么,但这是行不通的...我添加了你的修改后,我的投资记录保存了空白地址, –