granite icon indicating copy to clipboard operation
granite copied to clipboard

Foreign_key is nil but is set in DB

Open confact opened this issue 4 years ago • 2 comments

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

confact avatar May 25 '21 08:05 confact

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.

confact avatar May 25 '21 10:05 confact

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}

stufro avatar Oct 28 '23 10:10 stufro