-1

我正在使用Rails 3,omniauth和facebook圖形API構建教育應用程序的原型。所以當用戶登錄我的應用程序時,他使用他的Facebook帳戶,我抓住他所有的教育歷史和他的朋友education_history。group_by education-rails 3

我想組的每個用戶的朋友喜歡的教育是: enter image description here

我已經試過這樣的事情:

<ul class="friends-list"> 
<%= current_user.friends.group_by(&:highschool_name) do |highschool_name| 
p "<li>#{highschool_name}</li>" 
end 
%> 
</ul> 

而且我得到一個語法錯誤。

用戶TABEL這個樣子的:

[id, name, image, location, highschool_name, highschool_year, college_name, college_year, graduteschool_name, graduate_year ] 

而且朋友TABEL看起來是這樣的:

[id, uid, name, image, higschool_name, college_name, graduateschool_name, user_id] 

如何使用活動記錄,不循環,因爲它們並不有效性解決我的問題。 。 對?

+0

是什麼語法錯誤說? – DVG 2012-07-14 23:29:23

+0

@DVG,錯誤表示:塊arg和實際塊給出 – SHUMAcupcake 2012-07-14 23:32:43

+0

爲什麼downvote? – SHUMAcupcake 2012-07-15 14:56:57

回答

1

您不能在ERB文件中使用pputs。把ERB文件看作一個串聯在一起的大字符串。像"string 1" + "string 2" + "string 3"

這就是ERB所做的 - 它只是將字符串粘貼成一個大字符串。在連接操作中不能調用puts。因此,ERB文件中的所有內容都必須是字符串。由於puts調用不會返回字符串,因此puts調用的輸出只是「冒煙」,因此它會寫入stdout

接下來我們看一下group_by:它返回一個Hash

---------------------------------------------------- Enumerable#group_by 
    enum.group_by {| obj | block } => a_hash 
------------------------------------------------------------------------ 
    Returns a hash, which keys are evaluated result from the block, 
    and values are arrays of elements in enum corresponding to the key. 

     (1..6).group_by {|i| i%3} #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]} 

所以把一切在一起,我們可以做這樣的事情:

<% current_user.friends.group_by(&:highschool_name).each do |hsname, friends| %> 
    <% next if hsname.blank? %> 
    <li><%= hsname %></li> 
    <% friends.each do |friend| %> 
    <%= image_tag(friend.img_url) %> # <- Or wherever you get the img url from 
    <% end %> 
<% end %> 
+0

感謝那真棒解釋,我現在得到這個錯誤:undefined方法'highscool_name' – SHUMAcupcake 2012-07-14 23:45:40

+0

@SHUMAcupcake - 糟糕,是我的代碼中的一個錯字。重新加載最新的編輯。 – Casper 2012-07-14 23:49:16

+0

沒問題。它輸出第一個所有用戶的朋友,然後輸出每個highschool_name兩次爲每個用戶.. – SHUMAcupcake 2012-07-14 23:53:47