Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Foreign_key is nil but is set in DB #448

Open
confact opened this issue May 25, 2021 · 2 comments
Open

Foreign_key is nil but is set in DB #448

confact opened this issue May 25, 2021 · 2 comments

Comments

@confact
Copy link

confact commented May 25, 2021

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
Copy link
Author

confact commented May 25, 2021

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.

@stufro
Copy link
Contributor

stufro commented Oct 28, 2023

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}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants