0

How can I skip validation for nested_attribute if condition is true

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

then in 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

4 Answers 4

1

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 }

then in aquariums_controller.rb

def some_action
  @aquarium = Aquarium.new(aqua_params)
  @aquarium.skip_fishes_ratio_validation = true
  @aquarium.save
end
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Max for this. I've been searching for hours on the net, this is what I definitely need
Hi @romiesilvano ! You're welcome ! I'm glad to help ;)
1

You can just add the condition in method and check for the 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

Comments

0
@aquarium.save(validate: false)

I believe skips validations on the model.

2 Comments

But I need to run validation for some field, I just want to skip validation on specific field.
In which case, the easiest way would be a custom validation with a method that contains the condition to skip. I think Deepak has just posted what you'll need.
0

In Rails 5 you can simply pass optional: true to the belongs_to association.

So in your fish.rb, update association with the following code:

belongs_to :aquarium, optional: true

It will skip association validation if the fish object has no aquarium.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.