Skip to content

Commit 6fbd4b2

Browse files
authored
MONGOID-5457 Document + example of non-String field types in localized fields (#5444)
1 parent e731a1d commit 6fbd4b2

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

docs/reference/fields.txt

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1421,7 +1421,7 @@ Mongoid supports localized fields via `i18n <https://github.com/ruby-i18n/i18n>`
14211421

14221422
class Product
14231423
include Mongoid::Document
1424-
field :description, localize: true
1424+
field :description, type: String, localize: true
14251425
end
14261426

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

1450+
Localized fields can be used with any field type. For example, they can be used
1451+
with float fields for differences with currency:
1452+
1453+
.. code:: ruby
1454+
1455+
class Product
1456+
include Mongoid::Document
1457+
1458+
field :price, type: Float, localize: true
1459+
field :currency, type: String, localize: true
1460+
end
1461+
1462+
By creating the model in this way, we can separate the price from the currency
1463+
type, which allows you to use all of the number-related functionalities on the
1464+
price when querying or aggregating that field (provided that you index into the
1465+
stored translations hash). We can create an instance of this model as follows:
1466+
1467+
.. code:: ruby
1468+
1469+
product = Product.new
1470+
I18n.locale = :en
1471+
product.price = 1.00
1472+
product.currency = "$"
1473+
I18n.locale = :he
1474+
product.price = 3.24
1475+
product.currency = "₪"
1476+
1477+
product.attributes
1478+
# => { "price" => { "en" => 1.0, "he" => 3.24 }, "currency" => { "en" => "$", "he" => "₪" } }
1479+
14501480

14511481
.. _present-fields:
14521482

0 commit comments

Comments
 (0)