繁体   English   中英

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

[英]How to scope validation to specific model in polymorphic association.?

我有两个模型User and Investment和一个多模型模型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将适用于InvestmentUser但我希望仅适用于Investment而不适用于User 所以我该怎么做。

谢谢。

课堂上投资添加

validates :address_id, presence: true

并从地址类中删除波纹管

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

   protected

   def investment?
     addressable_type == 'Investment'
   end
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM