I have a legacy table with three fields: NAME, VALUE, ID. Naturally, the
primary key is NAME and not ID. The problem is that ActiveRecord updates
the NAME primary key when I try to set ID: object.id=1 will update the
NAME attribute and not the ID attribute. I can only update the ID
attribute via WRITE_ATTRIBUTE (see IRB example below).
I can work around this issue, but it breaks FactoryGirl (and presumably
others). Any thoughts on workarounds or if I'm doing something wrong?
Thanks!
Can you create a view in the legacy database to remap the field names?
If so, then your ActiveRecord model can just point to the view and
save you
a lot of headaches.
Seems like it ought to check and see if
set_primary_key = something other than "id"
is set in the model and behave accordingly (if "id" is not the model's
primary key, then don't remap attr_name to self.class.primary_key).
Of course, I've just looked at this one small snippet of code, and there
may be other places in the AR code base that use 'id' as a name alias
for the primary key (whatever it is), so removing that bit of
redirection might totally hose up AR.
[Please post responses below, not above, i.e. no top posting]
My suggestion to create a view would not affect other applications.
The whole point of the view is to create an abstraction for your
application without a side effect. So I will ask again, can you create
a view in your legacy database?
Thanks for the dope-slap that I should have looked in the code itself. I
should also have mentioned that this is using Rails 2.3.5. Turns out
that object.id is always going to point to the primary key.
module ActiveRecord
class Base
# Sets the primary ID.
def id=(value)
write_attribute(self.class.primary_key, value)
end
(not sure if I showed the hierarchy to the function correctly)
My suggestion to create a view would not affect other applications.
The whole point of the view is to create an abstraction for your
application without a side effect. So I will ask again, can you create
a view in your legacy database?
Thanks for clarifying, I didn't realize the distinction when I read your
message the first time. I don't know the answer but it certainly seems
like it should work.
Thanks to everyone for your help, very good ideas and very informative.
Much appreciated!