Let\'s work with these classes:
class User < ActiveRecord::Base
has_many :project_participations
has_many :projects, through: :project_participations,
Associations are defined on database level and make use of database table's primary key (and in polymorphic
cases, class name). In case of has_many :through
the lookup on association (say, User
's Project
s) is:
User
-Project
pairs, whose user_id
is a certain value (primary key of an existing User
in the database)project_id
(primary keys of projects) from these pairsProject
s by resulting keysOf course, these are simple terms, in database terms it's much shorter and uses more complicated abstractions, such as an inner join
, but the essence is the same.
When you create a new object via new
, it is not yet saved in the database, and therefore has no primary key (it's nil
). That said, if the object is not in a database yet, you have no way of referencing it from any ActiveRecord's association.
Side note:
There is a possibility, however, that a newly created (and not saved yet) object will act as if something is associated with it: it might show entries belonging to NULL
. This usually means you have an error in your database schema that allows such things to happen, but hypothetically, one could design his database to make use of this.