Skip to content

Commit c494c9a

Browse files
committed
MONGOID-5457 Document + example of non-String field types in localized fields (#5444)
1 parent 0e15747 commit c494c9a

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
@@ -1397,7 +1397,7 @@ Mongoid supports localized fields via `i18n <https://github.com/ruby-i18n/i18n>`
13971397

13981398
class Product
13991399
include Mongoid::Document
1400-
field :description, localize: true
1400+
field :description, type: String, localize: true
14011401
end
14021402

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

1426+
Localized fields can be used with any field type. For example, they can be used
1427+
with float fields for differences with currency:
1428+
1429+
.. code:: ruby
1430+
1431+
class Product
1432+
include Mongoid::Document
1433+
1434+
field :price, type: Float, localize: true
1435+
field :currency, type: String, localize: true
1436+
end
1437+
1438+
By creating the model in this way, we can separate the price from the currency
1439+
type, which allows you to use all of the number-related functionalities on the
1440+
price when querying or aggregating that field (provided that you index into the
1441+
stored translations hash). We can create an instance of this model as follows:
1442+
1443+
.. code:: ruby
1444+
1445+
product = Product.new
1446+
I18n.locale = :en
1447+
product.price = 1.00
1448+
product.currency = "$"
1449+
I18n.locale = :he
1450+
product.price = 3.24
1451+
product.currency = "₪"
1452+
1453+
product.attributes
1454+
# => { "price" => { "en" => 1.0, "he" => 3.24 }, "currency" => { "en" => "$", "he" => "₪" } }
1455+
14261456

14271457
Fallbacks
14281458
---------

0 commit comments

Comments
 (0)