2016-12-16 23 views
-4

我有一個學生收集結果集,我需要關注。 應按照以下規則解決顯示名稱:如果集合中沒有其他同名學生,則其顯示 名稱應該只是他們的名字。在rails中的顯示名稱應該包含名字和姓氏的首字母

  1. 如果集合中有多個同名學生,他們的顯示名應該是他們的名字,後跟一個空格,並且他們的最後一個首字母(例如「John Smith」解析爲「約翰S」)..
+0

你的結果是設置一個活動的記錄對象數組,或者你想在一個哈希中做? – Jayaprakash

+0

是的,它是一個活動的記錄關係結果集 – Nikhil

回答

0

試試這個

@results.each do |object| 
    displayname = (@results.select { |filter_object| filter_object.first_name == object.first_name }.count > 0) ? object.first_name : object.first_name + " " + object.last_name.initial 
end 
0

這裏是一個例子,這可能不是特別是你所需要的(這有點聽起來像功課),但希望它給你一個理念。

# in Student model 
attr_accessor :display_name 

# in controller 
students = Student.all 
students.each do |student| 
    if students.count { |s| s.first_name == student.first_name } > 1 
    student.display_name = s.first_name 
    else 
    student.display_name = "#{student.first_name} #{student.last_name[0].upcase}" 
    end 
end 

# in view 
<% students.each do |student| %> 
    <%= student.display_name %> 
<% end %> 
0

首先找出重複的名字。

dup_first_names = Student.select(:first_name).group(:first_name).group(:first_name).having("COUNT(*) > 1").uniq.pluck(:first_name) 

然後爲每個學生檢查名字是否在dup_first_names陣列中。

Student.all.each do |s| 
    if dup_first_names.include?(s.first_name) 
    puts "#{s.first_name} #{s.last_name.first}" 
    else 
    puts "#{s.first_name}" 
    end 
end 
相關問題