Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store array in attribute of ActiveRecord model?

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?

like image 224
petRUShka Avatar asked Feb 14 '23 15:02

petRUShka


1 Answers

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.

like image 58
AndyV Avatar answered Feb 17 '23 10:02

AndyV