I just realized one of my models has object_id
as a column, and that's going to cause prolems.
Any suggestions on possible alternatives for the name object_id
?
What is this column supposed to be mapping to? Is it a foreign key to an objects table?
Figure out what you're really trying to represent. It's probably not just any generic thing in the whole world. (If it is, maybe things is a better name.)
If you're working under constraints and you absolutely must have that object_id
column, you could still refer to it directly with attributes[:object_id]
and bypass Rails's magic methods.
As a last resort, you could overwrite the method with your own #object_id
method that simply returns that attribute from your database (this is what Rails did with the #id
method). I can't think of anything that would definitely break off the top of my head, but it's probably not a great idea. The object ID is used for a lot of miscellaneous things, so you may get strange behavior if you do object comparisons, use your object as a hash key, etc.
You don't need to use object_id
at in your model. And there should be no column named object_id
in the database.
object_id
is just a default methods that all (except BasicObject
in Ruby 1.9) objects have (see docs ).
Returns an integer identifier for obj. The same number will be returned on all calls to id for a given object, and no two active objects will share an id. Replaces the deprecated Object#id .
2.object_id # 5 or anything, but the same
2.id # NoMethodError: undefined method `id' for 2:Fixnum
2.object_id # 5
"anything has object_id".object_id # 22522080
"anything has object_id".object_id # 22447200 - string has different object_id because it's a new instance everytime
So, just use id
to access database identifier of ActiveRecord classes. That is the one created by Ruby On Rails for model objects.
OR if you do need to have the column in the database called object_id then you can create a method on the ActiveRecord model like this:
def general_id
read_attribute(:object_id)
end
I'm kind of surprised that Rails doesn't create __object_id__
as a reference to the original form of object_id
, like send
has a Ruby variant called __send__
.
Edit: The Ruby method __id__
appears to be the __send__
equivalent for object_id
. It may be safe to use object_id
as a method for your foreign key, or it may not. I don't actually use Rails in my current job.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.