Skip to content
This repository
Browse code

Runtime conditions for associations should use procs

The association guide previously recommended using a trick with single
quote delaying of string interpolation in order to handle setting association
conditions that would be evaluated at runtime. Using a proc is the new way as
this no longer works.
  • Loading branch information...
commit c4e29541724433fd1c96715bde829209066ca205 1 parent 3ca2696
authored October 11, 2011
6  railties/guides/source/association_basics.textile
Source Rendered
@@ -1229,17 +1229,15 @@ end
1229 1229
 
1230 1230
 If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@customer.confirmed_orders.create+ or +@customer.confirmed_orders.build+ will create orders where the confirmed column has the value +true+.
1231 1231
 
1232  
-If you need to evaluate conditions dynamically at runtime, you could use string interpolation in single quotes:
  1232
+If you need to evaluate conditions dynamically at runtime, use a proc:
1233 1233
 
1234 1234
 <ruby>
1235 1235
 class Customer < ActiveRecord::Base
1236 1236
   has_many :latest_orders, :class_name => "Order",
1237  
-    :conditions => 'orders.created_at > #{10.hours.ago.to_s(:db).inspect}'
  1237
+    :conditions => proc { "orders.created_at > #{10.hours.ago.to_s(:db).inspect}" }
1238 1238
 end
1239 1239
 </ruby>
1240 1240
 
1241  
-Be sure to use single quotes.
1242  
-
1243 1241
 h6(#has_many-counter_sql). +:counter_sql+
1244 1242
 
1245 1243
 Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.

0 notes on commit c4e2954

Please sign in to comment.
Something went wrong with that request. Please try again.