oaken icon indicating copy to clipboard operation
oaken copied to clipboard

Support UUID as IDs

Open marcelolx opened this issue 1 year ago • 2 comments

Something like this is needed, otherwise it won't pass the UUID as a string to find

marcelolx avatar Aug 22 '24 19:08 marcelolx

Huh, I see. It's possible we want to generate the method based on ActiveRecord::Base::primary_key.

Probably to support composite primary keys as well, which are an Array.

kaspth avatar Aug 22 '24 21:08 kaspth

Would "def #{label} = find(#{record.id.inspect})" solve the interpolation here? That'll keep integers plain, wrap UUID strings in quotes, and should handle array keys sanely as well (unless the composite key has eg. a Date column included).

jamie avatar Sep 13 '24 17:09 jamie

This is what I do in my seeding tool

data = {...} ## hash object of your data
if @model_class.primary_key.is_a?(Array)
  data[:id] = data.slice(*@model_class.primary_key.collect(&:to_sym)).values # id gets converted to an array
end
record = find_or_initialize_record(data)
record.assign_attributes(data)
record.save || raise(ActiveRecord::RecordNotSaved, "Record not saved!")

with rails 7.2 and above composite keys might have a column :id this might collied. so use :id_value to get the real column of :id on your active record model.

good thing about what I have is that it wont matter what your primary_keys look like it will create the correct :id value ..string, int, uuid or even an array of types example id = [:tenant_id , :id]

so using that knowledge I would switch from find -> find_by if the record.id is an array (composite key) it will still work

labels.each do |label, record|
  # switch to find_by :id if the record is a composite key, it will be passed.. also if  the key is a string or integer
  class_eval "def #{label} = find_by(id: record.id)", location.path, location.lineno
end

freibuis avatar Oct 23 '24 08:10 freibuis

@marcelolx hey, can you test it out on your end with #88 now?

I'll ship a new Oaken release shortly.

kaspth avatar Dec 17 '24 19:12 kaspth

@kaspth Running into this issue today. Any plans for a new release?

paulfri avatar Apr 17 '25 15:04 paulfri

@paulfri you got it! I kept meaning to do it, but just never got to it, but anyway here's https://github.com/kaspth/oaken/releases/tag/v0.8.0

kaspth avatar Apr 18 '25 15:04 kaspth

Thank you! 🙏

paulfri avatar Apr 18 '25 15:04 paulfri