在rails 3中的group_by highschool_name

时间:2012-07-15 23:17:51

标签: ruby-on-rails ruby ruby-on-rails-3

我正在尝试群组用户朋友的高中,用户用他的Facebook帐户登录,我使用脸谱图来获取他所有的朋友。

此代码首先输出/打印所有用户朋友,并由highschool打印每个朋友的群组。我不想要那个,我只想输出/打印这些组。

<ul class="friends-list">
<% current_user.friends.group_by(&:highschool_name).map do |hsname, friends| %>
   <li><%= hsname %></li> 
   <% friends.map do |friend| %>
   <%= image_tag(friend.image) %> 
 <% end %>
 <% end %>
</ul>

用户标签:

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

朋友表:

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

更详细的当前输出:

Started GET "/users/1" for 127.0.0.1 at 2012-07-16 01:10:17 +0200
Processing by UsersController#show as HTML
  Parameters: {"id"=>"1"}
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", "1"]]
  Rendered users/_profile_content.html.erb (0.6ms)
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
  Friend Load (9.2ms)  SELECT "friends".* FROM "friends" WHERE "friends"."user_id" = 1
  Rendered users/show.html.erb within layouts/application (287.4ms)
  Rendered layouts/_shim.html.erb (0.1ms)
  Rendered layouts/_header.html.erb (2.3ms)
  Rendered layouts/_footer.html.erb (0.6ms)
Completed 200 OK in 321ms (Views: 309.3ms | ActiveRecord: 9.8ms)

输出图像: http://postimage.org/image/tgyl9f27n/

2 个答案:

答案 0 :(得分:0)

我不知道我是否完全理解你的问题,但听起来你想列出每个小组的朋友。如果这是正确的,我认为你不需要第二个地图功能。

我认为它应该是for循环。

  <% current_user.friends.group_by(&:highschool_name).map do |hsname, friends| %>

       <li><%= hsname %></li> 
        <%for friend in friends%>
           <%= image_tag(friend.image) %> 
      <% end %>
   <% end %>

希望有所帮助

答案 1 :(得分:0)

问题: 数据库中的某些值为空。给出错误

解决方案:

<% next if hsname.blank? %>