I'd hate to say no, but there's no way to do that and keep following the Active Record pattern, which is a principle under the hood of Rails' ActiveRecord. As the Wikipedia article states:
an object instance is tied to a single row in the table
From that you can tell, that you cannot map a single object to multiple distinct rows.
Rails' ActiveRecord objects come in two different forms that look alike but work differently inside:
- Not persisted objects (results of
new
, association.build
and maybe some others)
They don't have id
s yet, they're not yet valid "Active Records", that implies that on save a new row in the database is created and the object is considered persisted from that moment.
- Persisted objects (received from the database in any way)
An object considered a valid row in the database without most implications. Any operation with that object should be reasonable in context of a RDBMS.
That said, to do that, you'd have to dive into the depths of AR implementation, because to "unpersist" an AR object (if you follow the pattern) you have to remove it from the database. No exceptions in current AR's implementation.
Here's a little experiment. Once we have an unpersisted object, we can examine it and find out it has an id
equal to nil
. Now let's get a persisted object and do this:
# assume we did `t = Thing.first` before
t.id = nil
t.save!
Create a new object? No! Update existing one!
UPDATE `things` SET `id` = NULL WHERE `things`.`id` = 1
Of course, DB rejects this query because it's not reasonable in terms of RDBMS to set primary key of any record to NULL
:
Column 'id' cannot be null
Why? See this question. Briefly, that's because NULL != NULL