如何在多态关联中将验证范围限定为特定模型。

时间:2014-02-06 06:47:17

标签: ruby-on-rails ruby

我有两个模型UserInvestment以及一个多态模型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 但我希望它仅适用于Investment而不是User。所以我该怎么做。

感谢。

2 个答案:

答案 0 :(得分:0)

类投资添加

validates :address_id, presence: true

并从类地址

中删除
validates :address, presence: true

答案 1 :(得分:0)

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

   protected

   def investment?
     addressable_type == 'Investment'
   end
end