对每个迭代器进行跟踪以显示所有关联属性



在这里我有 2 个模型
分支主题
,它们通过主题组具有多对多关系

控制台显示以下结果

~/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: "tSubject1t", 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: "Branch1t", 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: "tBranch2t", 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: "tBranch1t", created_at: "2017-05-06 23:06:32", updated_at: "2017-05-06 23:06:32">, #<Branch id: 2, name: "tBranch2t", created_at: "2017-05-06 23:06:32", updated_at: "2017-05-06 23:06:32">] 
2.3.0 :009 > 

我应该怎么做才能使结果像

=> "tBranch1t" "tBranch2t"

您可以尝试以下代码:

- 它将打印所有分支名称

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

-它将返回数组中的名称

s.branches.map(&:name)

最新更新