4

I have model waypoint with two attributes

  1. coordinates
  2. geocode_text

And model route that is no more than sorted array of waypoints with some additional text info. Some routes can have same waypoints, so I want to separate waypoints from routes.

What is the best way to store waypoints inside route?

I see several ways:

  • serialize waypoints ids to waypoint_ids attribute of route, but in such situation I will not be able to get route and all his waypoints in one SQL request, because waypoint ids will be hidden in serialized string.
  • create some third model that have such arguments

    1. route_id
    2. waypoint_id
    3. position

    Connect routes and waypoints with many-to-many association and store position of waypoint in route in position attribute. But it seems to be over-complicated.

What is the best way for me in such situation?

0

3 Answers 3

6
+50

I'd opt for the second option -- use a join table (RouteWaypoints) with something like acts_as_list so that you can retrieve the Route with all it's Waypoints correctly sorted. This isn't overkill -- the DB is really good at this stuff.

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately acts_as_list is buggy and don't work correctly with even has_many association: github.com/swanandp/acts_as_list/pull/85
1

Those several ways are both viable in your situation. So, to help you, I would just give you the pros and cons of serialization. Then, you'l be able to make a choice

  • First, freshly new grad, I was taught to not break the 1NF. If you choose serialization you'll have to forget using SQL aggregation functions on it (MIN, MAX, AVG).
  • If there is a large amount of associations between the two models, serialization might make read/write operations slower than a many-to-many associations. Also, you have to think about how often you are willing to update those data.

Personally, I'd just use serialization in cases where I deal with smaller components in my application (user_settings etc) and in which you do not want to read/write its info a lot. Here routes and waypoints seem to be quiet the core...

Hope it helps..

Comments

1

You data model fits in has many through activerecord relationship. This is the bestway as it give you flexibility in storing much addtional data and do indexing and construction sql queries.

Route.include(:way_points) is going to get load the given route and its waypoints, Once you have defined the relation.

In the joining model you can save the sort order, the additional info and linking to route and way points without changing either of the models.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.