madeintandem / jsonb_accessor

Adds typed jsonb backed fields to your ActiveRecord models.
MIT License
1.11k stars 93 forks source link

Raising error when avoid selecting jsonb field #145

Closed beetlegius-jt closed 2 years ago

beetlegius-jt commented 2 years ago

Hi! I'm reporting this error from the latest update (1.3.3) because it's raising an exception when trying to initialize a record by excluding the jsonb field.

Example:

# config/schema.rb

create_table "products", force: :cascade do |t|
  t.string "name"
  t.jsonb "data"
  t.datetime "created_at", precision: 6, null: false
  t.datetime "updated_at", precision: 6, null: false
end
# app/models/product.rb

class Product < ApplicationRecord
  jsonb_accessor :data, price: :integer
end
irb(main):002:0> product = Product.create!(name: "example", price: 123)
  TRANSACTION (0.3ms)  BEGIN
  Product Create (0.6ms)  INSERT INTO "products" ("name", "data", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["name", "example"], ["data", "{\"price\":123}"], ["created_at", "2022-02-02 11:24:28.837506"], ["updated_at", "2022-02-02 11:24:28.837506"]]
  TRANSACTION (7.1ms)  COMMIT                                                       
=>                                                                                  
#<Product:0x000055925492e0a0                                                        
...                                                                                 
irb(main):003:0> product.price
=> 123
irb(main):004:0> Product.select(:name).last
  Product Load (0.7ms)  SELECT "products"."name" FROM "products" ORDER BY "products"."id" DESC LIMIT $1  [["LIMIT", 1]]
/home/beetlegius/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/activemodel-7.0.1/lib/active_model/attribute.rb:226:in `value': missing attribute: data (ActiveModel::MissingAttributeError)
haffla commented 2 years ago

Hi @beetlegius,

there has been in fact a regression in the last release. I've identified the problem and will release a fix shortly. It's because you only select certain fields but not the jsonb field => Product.select(:name).

haffla commented 2 years ago

I've just released https://rubygems.org/gems/jsonb_accessor/versions/1.3.4. Thanks for reporting.

beetlegius-jt commented 2 years ago

Thanks so much! I've already updated that version and it's working fine! 👏👏👏