How to save a reorganizing range?

Hi all

I have a relation @user.tracks,

track(user_id:integer, point:integer, track_name:string)

I want to reorganizing all user’s track.point from integer to range.

Another words,


array = [1,4,10,14,22]


array = [0…1, 2…4, 5…10, 11…14, 15…22]

My code is:

@points = @user.tracks.pluck(:point).unshift(-1)

@ranges = @points.each_cons(2).map{|a,b| a+1…b} #=>[0…1, 2…4, 5…10, 11…14, 15…22]


Now i want to save a range for every user.tracks, but don’t know how?

First think: create a model track_range(track_id:integer, t_start:integer, t_end:integer) through has_one relation with track model. I see that @track.point = @track.track_range.t_end, but how could i set up and save track_range.t_start?

Second think(more acceptable), create a new column for track (pre_point:integer). But question the same: how to save a range from @ranges for each tracks?

Thanks for answers

It is usually a bad idea to add data to the database where that data
only depends on other data already existing in the db. By doing that
you end up with a de-normalised database. There are many problems
with this, consider for example that each time one of the existing
records changes you would have to re-calculate the the range data.
What would happen if the server crashed between the two changes? You
have the possibility of inconsistent data. Therefore you have to
start putting strategies in place to ensure this cannot happen, or to
cope with it if it does happen. It is usually much better just to
work out what you need when you need it. If it turns out that this
causes unacceptable performance then is the time to address that
issue, and not before.

If I understand your problem correctly is not the range for one track
point easily determined by finding the preceeding point for that

If I understand the issue correctly you might be better to have just
the track name in the track table (plus any other usefull data) then
have a points table with Track has_many points. Also User has_many
tracks as (I presume) you currently have.