原始代码,严重需要重构,某人说过,代码重复不过 3(说明:各个表和 user 这个表都是多对多的关系,CourseUser 就是关联表)
UN_GRADUATION_TYPE = "本科生"
GRADUATION_TYPE = "研究生"
@courseUsers = Array.new
CourseUser.where("check_status < ?", 1).dup.each do |au|
if au.course.stu_type == GRADUATION_TYPE
@courseUsers.append(au)
end
end
@aboardUsers = Array.new
AboardUser.where("check_status < ?", 1).dup.each do |au|
if au.aboard.stu_type == GRADUATION_TYPE
@aboardUsers.append(au)
end
end
@awardUsers = Array.new
AwardUser.where("check_status < ?", 1).dup.each do |au|
if au.award.stu_type == GRADUATION_TYPE
@awardUsers.append(au)
end
end
@punishmentUsers = Array.new
PunishmentUser.where("check_status < ?", 1).dup.each do |au|
if au.punishment.stu_type == GRADUATION_TYPE
@punishmentUsers.append(au)
end
end
@researchUsers = Array.new
ResearchUser.where("check_status < ?", 1).dup.each do |au|
if au.research.stu_type == GRADUATION_TYPE
@researchUsers.append(au)
end
end
@serviceUsers = Array.new
ServiceUser.where("check_status < ?", 1).dup.each do |au|
if au.service.stu_type == GRADUATION_TYPE
@serviceUsers.append(au)
end
end
@patentUsers = Array.new
PatentUser.where("check_status < ?", 1).dup.each do |au|
if au.patent.stu_type == GRADUATION_TYPE
@patentUsers.append(au)
end
end
我的最初方案:
private
def get_graduation_type_records_without_relation(class_name, str2)
@tmpUsers = Array.new
class_name.where("check_status < ?", 1).dup.each do |au|
if au.str2.stu_type == GRADUATION_TYPE
@tmpUsers.append(au)
end
end
@tmpUsers
end
问题就在 if au.str2.stu_type == GRADUATION_TYPE, 这里 str2 不能作为属性调用。 请问怎么重构最好?