2017-05-14 1 views
0

Hier habe ich zwei Modelle
Niederlassung und Gegenstand
dieSchienen jeder Iterator zeigen alle der Verein attrbute

Die Konsole zeigt folgendes Ergebnis

~/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]] 
durch subjectgroup zu viele Beziehung viele haben

=> "\ 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 > 

Was sollte ich versuchen, das Ergebnis wie

=> "\tBranch1\t" "\tBranch2\t" 
+0

Würde 's.branches.map (&: Name)' Ihre Bedürfnisse? – spickermann

+0

oh ja. Danke, aber warum funktioniert jede Schleife nicht? –

+0

http://stackoverflow.com/questions/5254128/arrayeach-vs-arraymap –

Antwort

0

Sie können auszukommen folgenden Code:

-Es Druckt alle Filialnamen

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

-Es wird wieder die Namen in Array

s.branches.map(&:name)