How to compare time from existing records in rails 4 and mongoid -


lets say, user has task in database. task's attributes week_day: 'monday', start_at: '12:30', ends_at: '13:30' new task should not assigned same user @ time duration. how achieve this. appreciate :)

class user   has_many :tasks end  class task   belongs_to :user   field :week_day,  type: string    # e.g 'monday'   field :starts_at, type: string    # e.g '13:00'   field :ends_at,   type: string    # e.g '13:30'   field :user_id end 

presumably intervals don't cross day boundaries don't have worry that. presence of separate day of week field sort of implies this.

you'll need have validations ensure both starts_at , ends_at exist , have right format. you'll need ensure starts_at strictly less ends_at times make sense.

luckily hh:mm format compares (i.e. '11:02' < '13:42' strings) can use simple string operators compare times.

that leaves overlaps. given 2 open intervals, (a, b) , (c, d), how can overlap? couple simple diagrams should help:

(a----b)-----     (1) ----(c-----d)  ----(a-----b)     (2) (c----d)-----  (a---------b)     (3) ---(c--d)----  ---(a--b)----     (4) (c---------d) 

we have variants of above a == c or b == d don't have treat specially, can use inclusive inequality tests.

1 , 3 can taken care of simple a <= c <= b check, 2 , 4 can taken care of checking c <= <= d.

if call new interval (a, b) want make sure there aren't (c, d) intervals in database person on day satisfy above inequalities. translating mongoid have:

# user's tasks on day care about. base = class.where(:user_id => user_id, :week_day => week_day)  if(base.where(:starts_at.gte => starts_at, :starts_at.lte => ends_at).exists?)   # overlap because <= c <= b, report error. elsif(base.where(:starts_at.lte => starts_at, :ends_at.gte => starts_at).exists?)   # overlap because c <= <= d, report error. end 

this is, of course, subject race conditions client-side validations. if want safe, you'd have push logic database using sort of unique index , you'd have store time intervals in different format satisfy mongodb's limited capabilities.


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -