Skip to content

Commit 6debd54

Browse files
authored
Merge pull request rails#49156 from gmcgibbon/cpk_fixtures
Add composite primary key examples to fixture docs
2 parents 0ee9580 + cd1289d commit 6debd54

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

activerecord/lib/active_record/fixtures.rb

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -456,6 +456,41 @@ class FixtureClassNotFound < ActiveRecord::ActiveRecordError # :nodoc:
456456
# In the above example, 'base' will be ignored when creating fixtures.
457457
# This can be used for common attributes inheriting.
458458
#
459+
# == Composite Primary Key Fixtures
460+
#
461+
# Fixtures for composite primary key tables are fairly similar to normal tables.
462+
# When using an id column, the column may be omitted as usual:
463+
#
464+
# # app/models/book.rb
465+
# class Book < ApplicationRecord
466+
# self.primary_key = [:author_id, :id]
467+
# belongs_to :author
468+
# end
469+
#
470+
# # books.yml
471+
# alices_adventure_in_wonderland:
472+
# author_id: <%= ActiveRecord::FixtureSet.identify(:lewis_carroll) %>
473+
# title: "Alice's Adventures in Wonderland"
474+
#
475+
# However, in order to support composite primary key relationships,
476+
# you must use the `composite_identify` method:
477+
#
478+
# # app/models/book_orders.rb
479+
# class BookOrder < ApplicationRecord
480+
# self.primary_key = [:shop_id, :id]
481+
# belongs_to :order, query_constraints: [:shop_id, :order_id]
482+
# belongs_to :book, query_constraints: [:author_id, :book_id]
483+
# end
484+
#
485+
# # book_orders.yml
486+
# alices_adventure_in_wonderland_in_books:
487+
# author: lewis_carroll
488+
# book_id: <%= ActiveRecord::FixtureSet.composite_identify(
489+
# :alices_adventure_in_wonderland, Book.primary_key)[:id] %>
490+
# shop: book_store
491+
# order_id: <%= ActiveRecord::FixtureSet.composite_identify(
492+
# :books, Order.primary_key)[:id] %>
493+
#
459494
# == Configure the fixture model class
460495
#
461496
# It's possible to set the fixture's model class directly in the YAML file.

0 commit comments

Comments
 (0)