arrays - Rails | Elegant way of looping through and saving json post data -
i posting ajax request on click action , json data looks this;
{"data"=>{"0"=>{"seasons"=>{ "0"=>{"from"=>"2017-01-04", "to"=>"2017-01-07", "weekday"=>"1", "per_day"=>"100", "weekly"=>"230", "weekend"=>"200", "available"=>"false", "check_in"=>"08:00", "check_out"=>"08:00", "sevendays"=>"false", "checkin_day"=>""}, "1"=>{"from"=>"2017-01-17", "to"=>"2017-01-20", "weekday"=>"1", "per_day"=>"250", "weekly"=>"323", "weekend"=>"300", "available"=>"false", "check_in"=>"08:30", "check_out"=>"08:00", "sevendays"=>"false", "checkin_day"=>""}, "2"=>{"from"=>"2017-02-01", "to"=>"2017-02-04", "weekday"=>"1", "per_day"=>"100", "weekly"=>"500", "weekend"=>"230", "available"=>"false", "check_in"=>"08:00", "check_out"=>"07:30", "sevendays"=>"false", "checkin_day"=>""}}} }
i need loop through from
& to
fields if overlap. know there function can use like, (from1..to1).overlaps?(from2..to2)
if overlap should return json error, fine.
another thing instance, per_day can't nil, how should loop through see validation not met. if eveything fine save database.
thank
(first of all, note input data in provided example converted ruby hash, not json.)
to loop through from
, to
fields returning boolean indicating whether of date ranges overlap (assuming x
input data):
require 'date' any_overlap = x['data']['0']['seasons']. # parse 'from' , 'to' range of dates map{|k, v| date.parse(v['from'])..date.parse(v['to']) }. # sort start date sort_by(&:begin). # compare each consecutive pair of dates each_cons(2). # return true if pair has overlapping begin/end dates any? { |x, y| x.end > y.begin }
to loop through input, returning boolean indicating whether of per_day
values nil
:
any_nil = x['data']['0']['seasons'].any?{|k, v| v['per_day'].nil?}
as elegant way of persisting input database if fine, depends on how intend input mapped existing database schema, , content of existing models (which need include in question more complete answer part). require placing overlapping-ranges code in custom active record validation procedure (you can use existing presence
validation validate not-nil).
Comments
Post a Comment