モデルの関連性は、このようになっています。
学科(Subject)のデータを作成
rails console
subject_names = %w(工学部 農学部 国際学部)
subject_names.each do |subject_name|
Subject.create(name: subject_name)
end
データがあることを確認
SELECT * FROM subjects;
ブラウザからは、このURLで確認できます。
http://192.168.33.10:3000/subjects
生徒(Student)のデータを作成
Google Docsに書かれているようにデータを入れていきます。
def google_docs_age(n)
case n
when 1 then 19
when 2, 6 then 20
when 3, 7 then 21
when 4, 8 then 22
when 6 then 25
when 9 then 24
when 10 then 28
else 30
end
end
def google_docs_subject_id(n)
case n
when 1, 7, 10 then 1
when 2, 8 then 2
when 3, 4, 5, 6, 9 then 3
else 3
end
end
(1..10).each do |num|
gen = num % 2 == 1 ? 0 : 1
docs_age = google_docs_age(num)
docs_subject_id = google_docs_subject_id(num)
sub = Subject.find(docs_subject_id)
user = Student.create(subject: sub, name: "山田#{num}太郎", email: "cebu_college+#{num}@gmail.com", gender: gen, age: docs_age, opinion: "その他#{num}")
end
データがあることを確認
SELECT * FROM students;
ブラウザからは、このURLで確認できます。
http://192.168.33.10:3000/students
試験結果(ExamResult)のデータを作成
def google_docs_exam(n)
case n
when 1, 10 then '英語'
when 2, 8 then '心理学'
when 3, 11, 14 then 'フランス語'
when 4, 9 then 'ジェンダー学'
when 5, 7, 13 then '体育'
when 6, 12, 15 then 'ドイツ語'
else '英語'
end
end
def google_docs_student(n)
student_id =
case n
when 1, 2 then 1
when 3, 4, 5 then 2
when 6 then 3
when 7 then 4
when 8 then 5
when 9 then 6
when 10 then 7
when 11 then 8
when 12 then 9
when 13, 14, 15 then 10
else 1
end
student = Student.find(student_id)
end
def google_docs_score(n)
case n
when 1 then 90
when 2 then 80
when 3 then 88
when 4 then 80
when 5 then 60
when 6 then 74
when 7 then 70
when 8 then 35
when 9 then 98
when 10 then 99
when 11 then 75
when 12 then 85
when 13 then 100
when 14 then 32
when 15 then 41
else 0
end
end
(1..15).each do |num|
exam = google_docs_exam(num)
stu = google_docs_student(num)
sc = google_docs_score(num)
ExamResult.create(name: exam, student: stu, score: sc)
end
データがあることを確認
SELECT id, student_id, name, score FROM exam_results;
ブラウザからは、このURLで確認できます。
http://192.168.33.10:3000/exam_results
サークルのデータを作成
club_names = %w(サッカー 囲碁 野球 柔道 将棋 空手)
club_names.each do |club_name|
Club.create(name: club_name)
end
データの確認
SELECT id, name FROM clubs;
ブラウザからは、このURLで確認できます。
http://192.168.33.10:3000/clubs
生徒とサークルを関連づけるデータを作成
def google_docs_club(n)
case n
when 1 then
%w(サッカー 囲碁)
when 2 then
%w(野球)
when 3 then
%w(柔道 空手)
when 6 then
%w(将棋 サッカー)
when 7 then
%w(サッカー)
when 8 then
%w(野球)
when 9 then
%w(空手)
when 10 then
%w(柔道 空手 囲碁)
end
end
(1..10).each do |num|
student = Student.find_by_name("山田#{num}太郎")
club_names = google_docs_club(num)
if club_names
club_names.each do |club_name|
club = Club.find_by_name(club_name)
ClubStudent.create(student_id: student.id, club_id: club.id)
end
end
end
確認用のSQL
SELECT
students.name,
clubs.name
FROM students
INNER JOIN club_students
ON students.id = club_students.student_id
INNER JOIN clubs
ON club_students.club_id = clubs.id
ORDER BY students.id ASC;