granite
granite copied to clipboard
Foreign_key is nil but is set in DB
I have a belongs_to with a foreign_key called obj_id in a model. The foreign key is set to an INT but when I do:
Model.find(26)
It returns:
#<Model:0x10f064d80 @_current_callback=nil @error=[], @new_record=false, @destroyed=false, @id=26, @obj_id=nil created_at=nil, updated_at=nil>
created at and updated at are also set in the database.
The model:
class Model < Granite::Base
connection pg
table models
belongs_to user : User, foreign_key: obj_id : Int32?
timestamps
end
The issue seems to be connected to connection setting. When I removed it in the model so it use default it seems to work.
Very strange but I think I got it working now.
I haven't been able to recreate this issue using version 0.23.2 of Granite and both sqlite or pg adapters - @confact is this still an issue for you?
I've added the script I used to try to reproduce this in case you think I'm missing something.
Reproduction script
require "pg"
Granite::Connections << Granite::Adapter::Pg.new(name: "test", url: "postgresql://localhost:5432/granite-tmp")
require "granite"
require "granite/adapter/pg"
class User < Granite::Base
connection test
table users
column id : Int32, primary: true
column foo : String
end
class Model < Granite::Base
connection test
table models
column id : Int32, primary: true
belongs_to user : User, foreign_key: obj_id : Int32
timestamps
end
User.migrator.drop_and_create
Model.migrator.drop_and_create
user = User.create(foo: "bar")
model = Model.create(obj_id: user.id)
puts Model.find!(model.id).to_h
# => {"id" => 1, "obj_id" => 1, "created_at" => 2023-10-28 10:18:40.0 UTC, "updated_at" => 2023-10-28 10:18:40.0 UTC}