Before save action and validation

My application has a logic: Parent model before save generates child model elements.

I'd like to validate before save parent element that it has at least one child element.

I tried use validates_presence_of, but it called before 'before_save' so parent doesn't have child elements.

Could you please tell me where I should generate child elements and where validate presence or absence of child elements?

Answers


Correct me if I misunderstood your problem, but you want to check if Parent model has at least 1 child before the Parent model triggers 'before_save' callback (which will do whatever it wants), right?

If yes, you can use 'before_validation' callback. 'before_validation' is called before 'before_save'. So you can do something like:

before_validation { self.errors.add(:base, 'error here or something') if self.children.count < 1 }

Note that rails will not even try to save the resource if resource's 'errors' array is not empty (so before_save callback will not be called). doing 'self.errors.add' in the 'before_save' callback will not stop the resource from being saved. If you want to stop the resource from being saved from the 'before_save' callback you can do:

before_save do 
  self.errors.add(:base, 'error here or something')
  false
end

Hope that helped. :)

Cheers!


Something like this:

class Hero < ActiveRecord::Base
  has_many :weapons

  before_save :check_equipment

  private
    def check_equipment
      errors.add(:weapons, "are not equipped") if weapons.size < 1 
    end
end

class Weapon < ActiveRecord::Base
  belongs_to :hero
end

You can create weapon as independent object and then associate the weapon with heros, or you can also create weapon with the hero just use accepts_nested_attributes_for method. The solution depends on you application architecture.


Need Your Help

WPF Image source turns null by itself

wpf image canvas

I have a Canvas, into which I put Images, like:

What is the best way to use absolute paths in PHP?

php path

I have always used relative paths in PHP. Last time I have realized that there were something like absolute paths.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.