سؤال

for any model instance, there is an #object_id and #id - I know that they are not the same.

However, I'm not quite sure what makes them different and how they would each be used in context.

Please help clear this up!!

Thanks!

هل كانت مفيدة؟

المحلول 3

In short, :id is the default primary_key of a table.And object_id could be the foriegn_key unless you set a custom foreign_key.

For example,take these two table users and posts.The relation would be

user => has_many posts and

post => belongs to user

so in the posts table,we should create a foreign_key(in this case user_id) to make the relations works.

Hope it helps!

نصائح أخرى

In Rails, an ActiveRecord model instance has an id property that maps to the value stored in the id column of the database. This may be nil if the record hasn't been saved.

In Ruby, object_id is a value that represents the identity of the object in question. It is always populated with something since everything in Ruby is an object.

These two are not related. There may be several independent instances of a model, each with their own object_id value but an identical id.

If two variables refer to something with the same object_id, then they refer to exactly the same object.

It's rare to see object_id used in code, it's a Ruby internal that's hardly ever needed. Mostly it's to establish if you're talking about identical objects, or just equivalent ones.

You will, on the other hand, see id and similar values used frequently since that's the glue that holds your relational database together.

Everything (and i mean everything) in Ruby is an object. Each of these objects has an object_id, which is a value used to track them in memory, basically.

In Rails, model instances are automatically set up with methods to return their value from the corresponding column in the database. .id is one of these.

As far as using in context, generally you would not use object_id in your code, ever: it's an under-the-hood thing.

EDIT - as an aside, a common issue seen in older versions of ruby/rails (where the object_id method was actually called id, and was overridden by rail's id method) was caused by the fact that the object_id of nil is 4. So you would call id on a variable which you expected to be a model instance, but was actually nil, thus getting "4" back when you expected to get the id of a record from the database.

id is specific for ActiveModel record and it relates to id column in database. object_id is defined on Object and is unique for every single object created in the memory.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top