Francois Beausoleil
2006-Sep-08 15:45 UTC
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/
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk
-~----------~----~----~----~------~----~------~--~---
Bosko Milekic
2006-Sep-08 18:22 UTC
Re: has_many relationship extensions and scoping rules
On 9/8/06, Francois Beausoleil <francois.beausoleil-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:> 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...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 Milekic <bosko.milekic-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> http://www.crowdedweb.com/ --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk -~----------~----~----~----~------~----~------~--~---