LoginSignup
7
3

More than 5 years have passed since last update.

rails associationでlimitを使うときに、注意

Last updated at Posted at 2019-02-19

model定義

class Post < ApplicationRecord
  has_many :latest_comments, -> { limit 10 }, class_name: "Comment", foreign_key: :post_id
end

Postからlatest_commentsを取得

Post.all.each {|post| p post.latest_comments } 
Post.includes(:latest_comments).each {|post| p post.latest_comments }
Post.eager_load(:latest_comments).each {|post| p post.latest_comments }

上記の3つの結果が異なります。原因はincludes、eager_loadがlimitをサポートできないからです。

Post.includes(:latest_comments).first.latest_comments
Post.includes(:latest_comments).second.latest_comments

一個のpostだけ、取得する場合は、問題ないです。

7
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
3