いいえ、それらは交換可能ではなく、いくつかの実際の違いがあります。
belongs_to
外部キーがこのクラスのテーブルにあることを意味します。したがってbelongs_to
、外部キーを保持しているクラスにのみ参加できます。
has_one
このクラスを参照する別のテーブルに外部キーがあることを意味します。したがってhas_one
、別のテーブルの列によって参照されるクラスにのみ入ることができます。
だからこれは間違っています:
class Person < ActiveRecord::Base
has_one :cell # the cell table has a person_id
end
class Cell < ActiveRecord::Base
has_one :person # the person table has a cell_id
end
そしてこれも間違っています:
class Person < ActiveRecord::Base
belongs_to :cell # the person table has a cell_id
end
class Cell < ActiveRecord::Base
belongs_to :person # the cell table has a person_id
end
正しい方法は次のとおりです(フィールドCell
が含まれている場合person_id
):
class Person < ActiveRecord::Base
has_one :cell # the person table does not have 'joining' info
end
class Cell < ActiveRecord::Base
belongs_to :person # the cell table has a person_id
end
双方向の関連付けの場合、それぞれ1つが必要であり、適切なクラスに所属する必要があります。一方向の関連付けであっても、どちらを使用するかは重要です。