Journey

技術に関することと覚書と

hanamiで関連先のモデルにorderやlimitをかける方法

例えば User モデルが Post モデルを has_many している場合に、find_with_postsposts に対して orderlimit をかけたい場合があると思います。 その方法は公式のDocumentに書いていなかったので、自分がやっている方法を共有します。

def UsersRepository
  associations do
    has_many :posts
  end

  def find_with_posts(user_id)
    aggregate(:posts).where(
      users[:id].qualified.is(user_id)
    ).node(:posts) do |posts|
      posts.order(posts[:created_at].qualified.desc)
           .limit(5)
    end.map_to(User).to_a
  end
end

のような形で実現できます。 node のブロック内で任意のSQLを発行できます。この node メソッドの正体ですが、まずhanamiは ROM で作られています。 実際 aggregate の返り値は ROM::Relation::Graph というクラスを返します。 これに関するドキュメントは以下のリンクにあります。

https://rom-rb.org/learn/core/5.2/combines/#adjusted-combine

まだhanamiの記事は少ないのでどんどん増やしていきたいですね。