Forum: Ruby on Rails Can I tell if the associated record is new in a belongs_to s

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
6559f9b9607a89074ea5e238d31ffbc2?d=identicon&s=25 Kelly Felkins (Guest)
on 2006-06-03 23:46
(Received via mailing list)
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/As...
and a
client class declares
belongs_to<http://api.rubyonrails.com/classes/ActiveRecord/As....

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
C64e63b70be7dfed8b0742540b8b27e5?d=identicon&s=25 Mark Reginald James (Guest)
on 2006-06-04 03:47
(Received via mailing list)
Kelly Felkins wrote:
>
> 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.
This topic is locked and can not be replied to.