Has_many relationship extensions and scoping rules

Hi all !

Is this supposed to work ?

class Email < ActiveRecord::Base
has_many :to, :class_name => ‘Recipient’, :conditions =>
“recipients.source = ‘to’” do
def create!(*args)
with_scope(:create => {:source => ‘to’}) do
super
end
end

def build(*args)
  with_scope(:create => {:source => 'to'}) do
    super
  end
end

end
end

From my tests, if I call Email.to.create!, the recipient model
correctly has it’s source attribute set to ‘to’. On the other hand,
if I call #build, the recipient’s source is nil.

There must be something I’m doing wrong…

Thanks !

François Beausoleil
http://blog.teksol.info/
http://piston.rubyforge.org/

On 9/8/06, Francois B. [email protected] wrote:

  end

From my tests, if I call Email.to.create!, the recipient model
correctly has it’s source attribute set to ‘to’. On the other hand,
if I call #build, the recipient’s source is nil.

There must be something I’m doing wrong…

Using with_scope around build simply has no effect. with_scope is
used for scoping the SQL query, which does not make sense in the
context of build (which just builds up an instance). I think what you
want to do can be achieved by calling super, grabbing the returned
object, and forcibly setting the “source” attribute to your desired
value (“to”) before returning.


Bosko M. [email protected]
http://www.crowdedweb.com/