rails ActiveModel リレーション/ポリモーフィック

本稿について

本稿はサイト運営者が学んだことなどを記したメモの内容です。
全てが正確な情報とは限りません。ご注意ください。また修正するべき点は適時修正していきます
has_manyの参照に条件をつける
has_many  :histories, -> { where hidden: false }, class_name: “UserHistory"

[参考]


参照時に並び替えをする
belongs_to :task, -> { order('created_at DESC') }



中間テーブルを挟んでassociationをつける
class User < ApplicationRecord
  has_many :items, through: :user_item
end

class Item < ApplicationRecord
  has_many :users, through: :user_item
end

class UserItem < ApplicationRecord
  belongs_to :user
  belongs_to :item
end

has_oneで関連づけしたデータの作成
user.create_item(name: 'hoge')
user.build_item(name: 'hoge')

クラス名とは別の名前で関連付けをする
has_one :bank, class_name: ‘UserBank'

# user.bank



親が削除されたら子も削除する
class Child < ApplicationRecord
  belongs_to :parent
end

class Parent < ApplicationRecord
  has_many :childs, dependent: :destroy
end



polymorphic 
schemaの定義の段階でこれを書いておいた方がいい
(ridgepoleで実行できるかどうかは後ほど試す)
t.references :postable, polymorphic: true, index: true


class User < ApplicationRecord
  belongs_to :hoge_user, polymorphic: true

class HogeUser < ApplicationRecord
  has_one :user
end

polymorphicで through 紐付け
has_many :album_contents, as: contents
has_many :movies, through: :album_contents, source: :contents, source_type: 'Movie'
has_many :pictures, through: :album_contents, source: :contents, source_type: 'Picture'

  belongs_to :album
  belongs_to :contents, polymorphic: true

  has_many :album_contents, as: :contents

has_oneでも親から参照させる場合
  has_one :user, as: :hoge_user

a[参考]


polymorphicをincludesは基本的には使えないのでpreloadを使う

Model.preload(content: :contents).where(model_id: model_id)

[参考]

polymorphic先をincludesする方法もあるっぽいが模索中
Back