A JSON endpoint that feeds a calendar raised this:
RangeError: cannot get the first element of beginless rangeThe range came straight from the request, and the request had no start:
range = params[:start]..params[:end]What it means
The range has no beginning. A missing param is nil, and nil..x is valid Ruby: the Range docs call it a beginless range. Ruby has had them since 2.7, and endless ranges (x..nil) since 2.6. Building one doesn't raise. Asking it for its first element does (Ruby 3.4.10):
range = nil.."2026-10-31" # => .."2026-10-31"
range.begin # => nil
range.end # => "2026-10-31"
range.first # RangeError: cannot get the first element of beginless rangeA missing end is the mirror image. "2026-10-01"..nil is an endless range, and last raises cannot get the last element of endless range.
Why it happens
Nothing stops the range on its way in. Ruby builds it. range.present? is true, because every Range is present, even nil..nil. And ActiveRecord accepts it, turning the open end into a one-sided comparison (ActiveRecord 7.1.5.2 on PostgreSQL):
puts Event.where(starts_on: nil.."2026-10-31").to_sql
# SELECT "events".* FROM "events" WHERE "events"."starts_on" <= '2026-10-31'So where(starts_on: params[:start]..params[:end]) never raises, and the expression reads as safe. It breaks when anything else reads the range with first or last, or iterates it. The error is raised there, nowhere near the line that built the range.
It doesn't matter that your own JavaScript always sends both params. The endpoint answers any request, and it takes one without them.
The fix
Give each end of the range a default:
def date_range
start_date = parse_date(params[:start]) || Date.current.beginning_of_month
end_date = parse_date(params[:end]) || Date.current.end_of_month
start_date..end_date
end
def parse_date(value)
Date.iso8601(value.to_s)
rescue ArgumentError
nil
endparse_date returns nil for a missing, blank or invalid value (Date::Error is an ArgumentError), so that end falls back to its default and the range always has two real ends. The current month suits a calendar. For other endpoints, answering with a 400 is just as valid.
And when you're handed a range you didn't build, read it with begin and end. They return nil for an open end. first and last raise.