如果条件为真,我如何跳过对nested_attribute的验证
aquarium.rb
has_many :fishes
accepts_nested_attributes_for :fishes,
fish.rb
belongs_to :aquarium
validates :ratio, :numericality => { :greater_than => 0 }, if: :skip_this_validation
然后在aquariums_controller.rb
def some_action
@aquarium = Aquarium.new(aqua_params)
@aquarium.skip_this_validation = true # i know that this is not valid
#must skip validation for ratio and then save to DB
end
答案 0 :(得分:1)
您只需在方法中添加条件并检查conditional validation
即可class Fish < ActiveRecord::Base
validates :ratio, :numericality => { :greater_than => 0 }, if: :custom_validation
private
def custom_validation
# some_condition_here
true
end
end
答案 1 :(得分:0)
@aquarium.save(validate: false)
我相信会在模型上跳过验证。
答案 2 :(得分:0)
<强> aquarium.rb 强>
has_many :fishes
accepts_nested_attributes_for :fishes,
attr_accessor :skip_fishes_ratio_validation
<强> fish.rb 强>
belongs_to :aquarium
validates :ratio, :numericality => { :greater_than => 0 }, unless: proc { |f| f.aquarium&.skip_fishes_ratio_validation }
然后在 aquariums_controller.rb
def some_action
@aquarium = Aquarium.new(aqua_params)
@aquarium.skip_fishes_ratio_validation = true
@aquarium.save
end