mobility
mobility copied to clipboard
New Record created within a locale throws an error
When creating a new record, if you create it in the context of a locale, it will throw an error since it tries to set the translated column and not the original column. Is there a way to make it fall back to setting the original column if the record is new?
Context
# config/initializers/mobility.rb
Mobility.configure do
# PLUGINS
plugins do
backend :jsonb, column_suffix: '_i18n'
active_record
reader
writer
backend_reader
query
cache
fallbacks true
presence
locale_accessors
column_fallback true
end
end
# models/my_model.rb
class MyModel < ApplicationRecord
extend Mobility
translates :name
end
Expected Behavior
Ideally, when creating a new record, it would handle cases where the field hasn't already been set.
# rails c
Mobility.with_locale(:es) { MyModel.create(name: 'test') }
# If this worked
<MyModel:0x0000000134035518 id: 1, name: "test", name_i18n: { es: "test" }, created_at: ..., updated_at: ...>
Actual Behavior
# rails c
MyModel.create(name: 'test')
# This works fine and results in
<MyModel:0x0000000134035518 id: 1, name: "test", name_i18n: {}, created_at: ..., updated_at: ...>
# rails c
Mobility.with_locale(:es) { MyModel.create(name: 'test') }
# This does not work.
NoMethodError: undefined method `[]=' for nil
from /.rbenv/versions/3.3.1/lib/ruby/gems/3.3.0/gems/mobility-1.2.9/lib/mobility/backends/hash_valued.rb:24:in `write'
It makes sense that there is an issue as the original column never gets set, but it seems like Mobility should have a way to set a fallback for new records to just set the original column. Am I missing something here?
Possible Fix
Is there a configuration setting I am missing, or will I have to write a custom writer
method to handle this particular issue?