【发布时间】:2011-08-29 23:19:59
【问题描述】:
是否可以在 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 回调中这样做我感觉不太舒服,因为如果曲目列表也没有验证,我想实际取消播客创建。那我该怎么办?
【问题讨论】:
-
Inside Track 模型我们可以做这样的事情吗。
def valid? true end只需通过验证 -
我不希望绕过验证。我宁愿删除构建曲目列表的代码。 :)
标签: ruby-on-rails ruby-on-rails-3