Rails/ActiveRecord has_many through: association on unsaved objects

前端 未结 4 1606
囚心锁ツ
囚心锁ツ 2021-02-06 05:20

Let\'s work with these classes:

class User < ActiveRecord::Base
    has_many :project_participations
    has_many :projects, through: :project_participations,         


        
4条回答
  •  臣服心动
    2021-02-06 06:07

    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 Projects) is:

    1. Fetch all User-Project pairs, whose user_id is a certain value (primary key of an existing User in the database)
    2. Fetch all project_id (primary keys of projects) from these pairs
    3. Fetch all Projects by resulting keys

    Of 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.

提交回复
热议问题