標題の件で、has_manyしているモデルからincludeして取得する場合、limitは効かないのでしょうか?
ruby
1class User < ApplicationRecord 2 has_many :posts_limit -> { order('created_at DESC').limit(5) }, class_name: 'Post' 3end 4 5class Post < ApplicationRecord 6 belongs_to :user 7end
ruby
1class UsersController < ApplicationController 2 def index 3 @user = User.includes([:posts_limit]).first 4 @posts_limit = @user.posts_limit 5 # 5件以上取得している 6 end 7end
こちらのサイトなどでも、has_many
の場合はlimit
が効かないと言われていますが、本当にそうなのでしょうか?
(他のやり方はあるのでしょうか?)
http://stackoverflow.com/questions/33174701/rails-includes-a-has-many-relation-with-limit
また、上記のような、ユーザーに紐付いた記事を5件だけ取得したい場合は、改めてPostモデルから取得した方が良いのでしょうか?
申し訳ありませんが、宜しくお願い致します。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。