Skip to content

Commit f155f27

Browse files
p-mongokitopp
authored
Test & document MONGOID-5009 Belongs to relationship changes method visibility (#4912)
* Use public_send to delegate methods from Proxy to _target * Define respond_to_missing? to properly expose method visibility, since we are defining method_missing * forward all arguments * mark private * reinstate send * document the situation * remove respond_to_missing? from undefinitions Co-authored-by: Esteban Pastorino <ejpastorino@gmail.com> Co-authored-by: Oleg Pudeyev <oleg@bsdpower.com>
1 parent b173a6f commit f155f27

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

source/tutorials/mongoid-relations.txt

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1154,6 +1154,50 @@ For example:
11541154
has_many :orders
11551155
end
11561156

1157+
Association Proxies
1158+
-------------------
1159+
1160+
Associations employ transparent proxies to the target objects. This can
1161+
cause surprising behavior in some situations.
1162+
1163+
The method visibility may be lost when methods on association targets are
1164+
accessed, depending on the association:
1165+
1166+
.. code-block:: ruby
1167+
1168+
class Order
1169+
include Mongoid::Document
1170+
belongs_to :customer
1171+
1172+
private
1173+
1174+
def internal_status
1175+
'new'
1176+
end
1177+
end
1178+
1179+
class Customer
1180+
include Mongoid::Document
1181+
has_many :orders
1182+
1183+
private
1184+
1185+
def internal_id
1186+
42
1187+
end
1188+
end
1189+
1190+
order = Order.new
1191+
customer = Customer.create!(orders: [order])
1192+
1193+
# has_many does not permit calling private methods on the target
1194+
customer.orders.first.internal_status
1195+
# NoMethodError (private method `internal_status' called for #<Order:0x000055af2ec46c50>)
1196+
1197+
# belongs_to permits calling private methods on the target
1198+
order.customer.internal_id
1199+
# => 42
1200+
11571201
Association Metadata
11581202
====================
11591203

0 commit comments

Comments
 (0)