Browse files

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...
1 parent 78bab03 commit 2a73d00f4b0f6f5164267d141539d998163ba3d4 Stephen Pike committed with vijaydev Oct 11, 2011
Showing with 2 additions and 4 deletions.
  1. +2 −4 railties/guides/source/association_basics.textile
@@ -1229,17 +1229,15 @@ end
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 will create orders where the confirmed column has the value +true+.
-If you need to evaluate conditions dynamically at runtime, you could use string interpolation in single quotes:
+If you need to evaluate conditions dynamically at runtime, use a proc:
class Customer < ActiveRecord::Base
has_many :latest_orders, :class_name => "Order",
- :conditions => 'orders.created_at > #{10.hours.ago.to_s(:db).inspect}'
+ :conditions => proc { "orders.created_at > #{10.hours.ago.to_s(:db).inspect}" }
-Be sure to use single quotes.
h6(#has_many-counter_sql). +:counter_sql+
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 comments on commit 2a73d00

Please sign in to comment.