Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validations during ActiveRecord callbacks

Is it possible to perform validations when creating new instances of an associated model within a before_save callback in ruby?

class Podcast < ActiveRecord::Base
has_many :tracks, :dependent=>:destroy

before_save :generate_tracks

# creates the tracks played in the podcast 
def generate_tracks
    json = Hashie::Mash.new HTTParty.get("#{self.json_url}")
    json.sections.each do |section|
      if section.section_type=="track"
        track = self.tracks.build :name=>section.track.name
      end
    end
  end
end 

The above code works fine but I was hoping to add something like this inside the if statement:

unless track.valid?
  errors[:base] << "OOPS, something went wrong whilst trying to build tracklist."
  return false
end

The problem with this code is that track.valid? always returns false because the Track model validates the presence of podcast_id. I don't feel so comfortable doing this in an after_create callback because I want to actually cancel podcast creation if the tracklist doesn't validate too. So what can I do?

like image 384
stephenmurdoch Avatar asked Jul 27 '26 23:07

stephenmurdoch


1 Answers

Sounds to me as though what you want is validates_associated, which would let you do:

class Podcast < ActiveRecord::Base
  has_many :tracks

  validates_associated :tracks
end

That way, a podcast won't save unless it's associated tracks are valid.

like image 158
MrTheWalrus Avatar answered Jul 30 '26 18:07

MrTheWalrus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!