ActiveRecord回调期间的验证

时间:2011-08-29 05:18:59

标签: ruby-on-rails ruby-on-rails-3

在ruby中的before_save回调中创建关联模型的新实例时是否可以执行验证?

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 

上面的代码工作正常,但我希望在if语句中添加类似的内容:

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

此代码的问题是track.valid?始终返回false,因为Track模型验证了 podcast_id 的存在。在after_create回调中这样做我感觉不太舒服,因为如果跟踪列表也没有验证,我想要实际取消播客创建。那我该怎么办?

1 个答案:

答案 0 :(得分:2)

听起来好像你想要的是validates_associated,这可以让你做到:

class Podcast < ActiveRecord::Base
  has_many :tracks

  validates_associated :tracks
end

这样,除非关联的曲目有效,否则播客不会保存。