0

Here I have 2 models
Branch and Subject
which have many to many relationship through subjectgroup

The console shows the following result

~/workspace (master) $ rails c
Running via Spring preloader in process 4541
Loading development environment (Rails 4.2.7.1)
irb: warn: can't alias context from irb_context.

2.3.0 :001 > s=Subject.first
Subject Load (0.6ms)  SELECT  "subjects".* FROM "subjects"  ORDER BY "subjects"."id" ASC LIMIT 1

=> #<Subject id: 1, idx_id: nil, fullname: "\tSubject1\t", created_at: "2017-05-06 23:06:32", updated_at: "2017-05-06 23:06:32"> 

2.3.0 :002 > s.branches.first
Branch Load (0.9ms)  SELECT  "branches".* FROM "branches" INNER JOIN"subjectgroups" ON "branches"."id" = "subjectgroups"."branch_id" WHERE"subjectgroups"."subject_id" = $1  ORDER BY "branches"."id" ASC LIMIT 1 [["subject_id", 1]]

=> #<Branch id: 1, name: "\Branch1\t", created_at: "2017-05-06 23:06:32", updated_at: "2017-05-06 23:06:32">

2.3.0 :003 > s.branches.find(2)
Branch Load (0.6ms)  SELECT  "branches".* FROM "branches" INNER JOIN "subjectgroups" ON "branches"."id" = "subjectgroups"."branch_id" WHERE "subjectgroups"."subject_id" = $1 AND "branches"."id" = $2 LIMIT 1  [["subject_id", 1], ["id", 2]]

=> #<Branch id: 2, name: "\tBranch2\t", created_at: "2017-05-06 23:06:32", updated_at: "2017-05-06 23:06:32"> 

2.3.0 :004 > s.branches.first.name
Branch Load (0.7ms)  SELECT  "branches".* FROM "branches" INNER JOIN "subjectgroups" ON "branches"."id" = "subjectgroups"."branch_id" WHERE "subjectgroups"."subject_id" = $1  ORDER BY "branches"."id" ASC LIMIT 1  [["subject_id", 1]]

=> "\tBranch1\t"

2.3.0 :005 > s.branches.find(2).name
Branch Load (0.7ms)  SELECT  "branches".* FROM "branches" INNER JOIN "subjectgroups" ON "branches"."id" = "subjectgroups"."branch_id" WHERE "subjectgroups"."subject_id" = $1 AND "branches"."id" = $2 LIMIT 1  [["subject_id", 1], ["id", 2]]

=> "\tBranch2\t"

2.3.0 :006 > s.branches.each do |branch|
2.3.0 :007 >     branch.name
2.3.0 :008?>   end
Branch Load (0.5ms)  SELECT "branches".* FROM "branches" INNER JOIN "subjectgroups" ON "branches"."id" = "subjectgroups"."branch_id" WHERE "subjectgroups"."subject_id" = $1  [["subject_id", 1]]

=> [#<Branch id: 1, name: "\tBranch1\t", created_at: "2017-05-06 23:06:32", updated_at: "2017-05-06 23:06:32">, #<Branch id: 2, name: "\tBranch2\t", created_at: "2017-05-06 23:06:32", updated_at: "2017-05-06 23:06:32">] 
2.3.0 :009 > 

What should I do to make the result like

=> "\tBranch1\t" "\tBranch2\t"
Chionn K
  • 21
  • 1
  • 9

1 Answers1

0

you can try following code:

-It will print all branch names

s.branches.each do |branch|
  puts branch.name
end 

-It will return the names in array

s.branches.map(&:name)
puneet18
  • 4,341
  • 2
  • 21
  • 27