On 14 January 2015 at 12:40, Psycho Shine <[email protected]> wrote: > 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, > from > array = [1,4,10,14,22] > do > 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] > @points.shift > > 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?
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 track? 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. Colin -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/CAL%3D0gLum47oCfGFCueKuuCk%2By3EO%2BGaKGwN%2Bw3J--pzB9xva3Q%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.

