覚書: Rails: ポリモーフィック関連のスキャフォールド
ruby 3.1.2p20
Rails 7.0.2.4
Bundler version 2.3.14
Railsガイド 2.9 ポリモーフィック関連付け
Rails 7 API: ActiveRecord::FixtureSet(翻訳)
gem install bundler -v "2.3.14"
rails new many_pict_app && cd many_pict_app
bin/rails g scaffold Product name
bin/rails g scaffold Employee name
bin/rails g scaffold Picture name imageable:belongs_to{polymorphic}
bin/rails db:migrate
class Employee < ApplicationRecord
has_many :pictures, as: :imageable
class Product < ApplicationRecord
has_many :pictures, as: :imageable
# test/fixtures/pictures.yml
# Employee one が Picture を1つ持つ。
# Product one が Picture を2つ持つ。
employee_pict_1:
name: Employee Pict 1
imageable: one (Employee)
product_pict_1:
name: Product Pict 1
imageable: one (Product)
product_pict_2:
name: Product Pict 2
imageable: one (Product)
bin/rails db:fixtures:load
bin/rails c
Picture.order(:name).pluck(:imageable_type, :imageable_id)
# e.g, => [["Employee", 980190962], ["Product", 980190962], ["Product", 980190962]]
# ※今回は Employee と Product の fixture がどちらも one なのでIDが同じになっている。
# imageable_type で所属先を判別できる。
Picture.first.imageable # e.g, => #<Product:...
Employee.first.pictures # => 1
Employee.first.pictures.first.name # => "Employee Pict 1"
Product.first.pictures.count # => 2
Product.first.pictures # => ...
以上です。
この記事が気に入ったらサポートをしてみませんか?