我有两个模型User
和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
适用于Investment
以及User
但我希望它仅适用于Investment
而不是User
。所以我该怎么做。
感谢。
答案 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