u16suzuの blog

日々学んだことのメモブログです。

ARの自己結合と関連をcreate

自己結合

自己テーブルを参照する関連も作ることができる

class AddColumnToPosts < ActiveRecord::Migration[6.0]
  def change
    add_reference :posts, :prev_post
    add_reference :posts, :next_post
  end
end
class Post < ApplicationRecord
  belongs_to :category

  has_many :prev_posts, class_name: "Post", foreign_key: "prev_post_id"
  belongs_to :next_post, class_name: "Post"
end

以下のメソッドが使えるようになる.

> Post.last.next_post
> Post.last.prev_posts

関連をcreate

# これだけでcommitされる
Category.last.posts.create( title: "a", body: "bb")