Rails 3: Should I explicitly save the object in the after_create callback?

Corresponding code: http://pastebin.com/EnLJUJ8G

class Task < ActiveRecord::Base after_create :check_room_schedule ... scope :for_date, lambda { |date| where(day: date) } scope :for_room, lambda { |room| where(room: room) } scope :room_stats, lambda { |room| where(room: room) } scope :gear_stats, lambda { |gear| where(gear: gear) } def check_room_schedule @tasks = Task.for_date(self.day).for_room(self.room).list_in_asc_order @self_position = @tasks.index(self) if @tasks.length <= 2 if @self_position == 0 self.notes = "There is another meeting in this room beginning at # {@tasks[1].begin.strftime("%I:%M%P")}." self.save end end end private def self.list_in_asc_order order('begin asc') end end 

I am making a small task application. Each task is assigned to a room. When I add a task, I want to use a callback to check if there are tasks in the same room before and after the task I just added (although my code only handles one case with an edge right now).

So, I decided to use after_create (since the user will manually check this if they edit it, therefore not after_save), so I could use two areas and a class method to request tasks on the same day in the room and order them by time. Then I find the object in the array and start using if statements.

I need to explicitly save the object. It is working. But it seems strange to me that I do this. I'm not too experienced (first application), so I'm not sure if it frowned, or if this is an agreement. I searched a bunch and looked through the directory, but I don't see anything so specific.

Thanks.

+6
source share
1 answer

This looks like a task for before_create for me. If you need to save your after_* , you probably should use the before_* .

In before_create you will not need to call save , since saving occurs after the callback code is executed.

Instead of saving a view request, if you receive 2 or more objects, you should request one object that will conflict before saving.

In the psuedo code that you have now:

 after creation now that I'm saved, find all tasks in my room and at my time did I find more than one? Am I the first one? yes: add note about another task, then save again no: everything is fine, no need to re-save any edits 

What you should have:

 before creation is there at least 1 task in this room at the same time? yes: add note about another task no: everything is fine, allow saving without modification 

Something else like this:

 before_create :check_room_schedule def check_room_schedule conflicting_task = Task.for_date(self.day) .for_room(self.room) .where(begin: self.begin) # unsure what logic you need here... .first if conflicting_task self.notes = "There is another meeting in this room beginning at #{conflicting_task.begin.strftime("%I:%M%P")}." end end 
+3
source

Source: https://habr.com/ru/post/926142/


All Articles