Kelly Felkins
2006-Jun-03 21:45 UTC
[Rails] Can I tell if the associated record is new in a belongs_to save?
In a belongs_to association, is there a way to tell if the associated object was newly created? Hopefully this will explain my question: A Firm class declares has_many<http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html#M000530>:clients and a client class declares belongs_to<http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html#M000532>:firm. Now you do the following: Create a new firm and add clients using firm.clients.create methods. Note both firm and clients are unsaved at this point. Then you save the firm. It appears the sequence of events is 1) save the firm 2) save the clients Is it possible for the clients to know if the firm was newly saved? By the time the client is being saved firm.new_record? is false. Any suggestions? Thanks, -Kelly -------------- next part -------------- An HTML attachment was scrubbed... URL: http://wrath.rubyonrails.org/pipermail/rails/attachments/20060603/cf0c2533/attachment.html
Mark Reginald James
2006-Jun-04 01:45 UTC
[Rails] Re: Can I tell if the associated record is new in a belongs_to save?
Kelly Felkins wrote:> In a belongs_to association, is there a way to tell if the associated > object was newly created? > > Hopefully this will explain my question: > > A Firm class declares has_many > <http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html#M000530> > :clients and a client class declares belongs_to > <http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html#M000532> > :firm. > > Now you do the following: > > Create a new firm and add clients using firm.clients.create methods. > Note both firm and clients are unsaved at this point. > > Then you save the firm. It appears the sequence of events is > > 1) save the firm > 2) save the clients > > Is it possible for the clients to know if the firm was newly saved? By > the time the client is being saved firm.new_record? is false.Firm instances will have an appropriately set boolean instance variable called @new_record_before_save, which the clients will be able to inspect if you add a reader method for it. But because this is undocumented, and so subject to change, it''d be better if you made your own by adding to the firm model something like: before_save("@newly_saved? = new_record?; true") after_save("@newly_saved? = false; true") # optional attr_reader :newly_saved? -- We develop, watch us RoR, in numbers too big to ignore.