-3

我有两个表格用户和朋友,

用户表如下所示:

[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]

我想按教育对用户朋友进行分组:

  • 按 highschool_name 将用户朋友分组
  • 按 College_name 将用户朋友分组
  • 按graduateschool_name 将用户朋友分组

就像我制作的这个 Photoshop 样机:

在此处输入图像描述

我是 Rails 3 的开发人员,想使用活动记录来做到这一点,欢迎任何提示或想法。

4

1 回答 1

1

您应该创建高中、大学和研究生院模型并使用与用户的关系。朋友数据应该在用户模型上。

所以你应该有

User
  has_many :friendships
  has_many :friends, :through => :friendships
  has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
  has_many :inverse_friends, :through => :inverse_friendships, :source => :user
  belongs_to :higschool
  belongs_to :college
  belongs_to :graduateschool

Friendship
  belongs_to :user
  belongs_to :friend, :class_name => "User"

Higschool
  has_many :users

College
  has_many :users

Graduateschool
  has_many :users

所以,现在我认为你可以做类似的事情。

@higschool_friends = Hash[]
current_user.friends.group_by(&:higschool) do | higschool, friends |
  @higschool_friends[higschool] = friends
end

@college_friends = Hash[]
current_user.friends.group_by(&:college) do | college, friends |
  @college_friends[college] = friends
end

@graduateschool_friends = Hash[]
current_user.friends.group_by(&:graduateschool) do | graduateschool, friends |
  @graduateschool_friends[graduateschool] = friends
end
于 2012-07-14T15:58:40.307 回答