Search code examples
sqlrubysequel

Retrieving records and manipulating them as Ruby objects


New to Sequel and SQL in general, so bear with me. I'm using Sequel's many_through_many plugin and I retrieve resources that are indirectly associated with particular tasks through groups, via a groups_tasks join table and a groups_resources join table. Then when I query task.resource on a Task dataset I get resource objects in Ruby, like so:

>>[#<Resource @values={:id=>2, :group_id=>nil, :display_name=>"some_name"}>, #<Resource @values={:id=>3, :group_id=>nil, :display_name=>"some_other_name"}>]

Now, I want to be able to add a new instance variable, schedule to these resource objects and do work on it in Ruby. However, every time I query task.resources for each task, Sequel is bringing resources objects in to ruby as different resource objects each time (which makes sense), despite being the same record in the database:

>>
"T3"
#<Resource:0x007fd4ca0c6fd8>
#<Resource:0x007fd4ca0c6920>
#<Resource:0x007fd4ca0c60d8>
#<Resource:0x007fd4ca0c57a0>


"T1"
#<Resource:0x007fd4ca0a4c08>
#<Resource:0x007fd4ca097f58>
#<Resource:0x007fd4ca097b48>


"T2"
#<Resource:0x007fd4ca085ba0>
#<Resource:0x007fd4ca0850d8>

I had wanted to just put a setter in class Resource and do resource.schedule = Schedule.new, but since they're all different objects, each resource is going to have a ton of different schedules. What's the most straightforward way to manipulate these resource objects client side, but maintain their task associations that I query from the server?


Solution

  • If I am understanding your question correctly, you want to retrieve Resource objects and then manipulate some attribute named schedule. I am not very familiar with Sequel, but looking over the docs it seems to work similarly to ActiveRecord.

    1. Set up your instance variable (I imagine using something like attr_accessor :schedule on the Resource class).

    2. Store the records in a variable, you will be working with same instance each time, rather than the new instance Sequel returns.