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

MONGOID-5457 Document + example of non-String field types in localized fields #5444

Merged
merged 1 commit into from
Aug 15, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion docs/reference/fields.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1402,7 +1402,7 @@ Mongoid supports localized fields via `i18n <https://github.com/ruby-i18n/i18n>`

class Product
include Mongoid::Document
field :description, localize: true
field :description, type: String, localize: true
end

By telling the field to ``localize``, Mongoid will under the covers store the field
Expand All @@ -1428,6 +1428,36 @@ You can get and set all the translations at once by using the corresponding ``_t
product.description_translations =
{ "en" => "Marvelous!", "de" => "Wunderbar!" }

Localized fields can be used with any field type. For example, they can be used
with float fields for differences with currency:

.. code:: ruby

class Product
include Mongoid::Document

field :price, type: Float, localize: true
field :currency, type: String, localize: true
end

By creating the model in this way, we can separate the price from the currency
type, which allows you to use all of the number-related functionalities on the
price when querying or aggregating that field (provided that you index into the
stored translations hash). We can create an instance of this model as follows:

.. code:: ruby

product = Product.new
I18n.locale = :en
product.price = 1.00
product.currency = "$"
I18n.locale = :he
product.price = 3.24
product.currency = "₪"

product.attributes
# => { "price" => { "en" => 1.0, "he" => 3.24 }, "currency" => { "en" => "$", "he" => "₪" } }


.. _present-fields:

Expand Down