Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAndrew Cottage
20,718 PointsRails Callback that Opens a New Thread, Checks a Condition, and Destroys Self if Condition is true.
Hello all.
I'm trying to write a callback that opens a new thread, checks a condition, and destroys self if condition is true.
after_create :verify_statute
def verify_statute
if Rails.env != 'test'
Thread.new do
sleep(15)
if self.statutes.empty?
self.destroy
end
end
end
end
I have it working but want to know if this is the correct way to require an associated record. Usually a record is created then a few seconds after that the associated record may or may not be created. If that association never gets created I want to destroy the original record. Also any ideas on how I would test a callback like this?
1 Answer
Ethan Lowry
Courses Plus Student 7,323 PointsThis seems like a slightly unusual use case - would a better option not be to set validation on the 'parent' model so that it cannot be created without the association being provided?
e.g. validates :statutes, presence: true
?
Andrew Cottage
20,718 PointsAndrew Cottage
20,718 PointsThanks for the reply Ethan.
That does seem better, but usually the statutes association is created within seconds of the parent model. It saves time for me to save the parent model before creating the statute association. I will look into refactoring my code to save everything at once and update the thread here if that is a working solution.
Thanks