以下では、 Idea と Comment のモデルでためしています。
app/modes/comment.rb を次の様に記載します。
ruby
1...
2 belongs_to :idea
3
4 scope :select_by_ideas, -> (ideas) {
5 where(idea_id: ideas.pluck(:id))
6 }
7
8 scope :select_by_idea_array, -> (idea_array) {
9 where(idea_id: idea_array.map(&:id))
10 }
11...
こうすると
Comment.select_by_ideas(Comment.limit(1))
や
Comment.select_by_ideas([cooment0, comment1])
のようにして、idea を指定して、それに紐ついているコメントを取得できます。
取得結果にさらに ActiveRecord のメソッドを適用することもできます。
rails console で試してみます。(table は事前に db:seed で投入済です)
ruby
1$ bundle exec rails c
2
3> Idea.select([:id, :name])
4 Idea Load (0.1ms) SELECT id, name FROM "ideas"
5=> [#<Idea id: 980190962, name: "IDEA_001">, #<Idea id: 102, name: "IDEA_002">]
6
7> Comment.select([:id, :idea_id])
8 Comment Load (0.1ms) SELECT id, idea_id FROM "comments"
9=> [#<Comment id: 200, idea_id: 102>, #<Comment id: 428300069, idea_id: 980190962>, #<Comment id: 554292058, idea_id: 980190962>]
10
11> Comment.select_by_ideas(Idea.limit(3)).select([:id, :idea_id]).limit(4)
12 (0.1ms) SELECT "ideas"."id" FROM "ideas" LIMIT 3
13 Comment Load (0.2ms) SELECT id, idea_id FROM "comments" WHERE "comments"."idea_id" IN (980190962, 102) LIMIT 4
14=> [#<Comment id: 200, idea_id: 102>, #<Comment id: 428300069, idea_id: 980190962>, #<Comment id: 554292058, idea_id: 980190962>]
15
16> idea0 = Idea.all[0]
17> idea1 = Idea.all[1]
18> Comment.select_by_idea_array([idea0, idea1]).select([:id, :idea_id]).limit(4)
19 Comment Load (0.2ms) SELECT id, idea_id FROM "comments" WHERE "comments"."idea_id" IN (102, 980190962) LIMIT 4
20=> [#<Comment id: 200, idea_id: 102>, #<Comment id: 428300069, idea_id: 980190962>, #<Comment id: 554292058, idea_id: 980190962>]
21
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2017/01/27 13:11