2014-02-13 71 views
0

查看用户的显示页面时,我想显示用户所在的团队,然后显示每个团队成员的数量。我正试图了解如何在模型中编写方法以实现此功能。如何为团队功能创建活动记录关联

class Membership < ActiveRecord::Base 
    attr_accessible :team_id, :user_id 
    belongs_to :team 
    belongs_to :user 
end 

class Team < ActiveRecord::Base 
    attr_accessible :name, :user_id 
    belongs_to :admin, :class_name => "User",:foreign_key => "user_id" 
    has_many :memberships 
    has_many :members, through: :memberships, source: :user 
    has_many :users, through: :memberships 
end 

class User < ActiveRecord::Base 
    belongs_to :team 
    has_many :teams, through: :memberships 
    has_many :memberships 
end 

ActiveRecord::Schema.define(:version => 20140211214838) do 


create_table "memberships", :force => true do |t| 
    t.integer "team_id" 
    t.integer "user_id" 
    t.datetime "created_at", :null => false 
    t.datetime "updated_at", :null => false 
end 


create_table "teams", :force => true do |t| 
    t.string "name" 
    t.integer "user_id" 
    t.datetime "created_at", :null => false 
    t.datetime "updated_at", :null => false 
end 

create_table "users", :force => true do |t| 
    t.string "email", :default => "", :null => false 
    t.string "encrypted_password", :default => "", :null => false 
    t.string "reset_password_token" 
    t.datetime "reset_password_sent_at" 
    t.datetime "remember_created_at" 
    t.integer "sign_in_count", :default => 0, :null => false 
    t.datetime "current_sign_in_at" 
    t.datetime "last_sign_in_at" 
    t.string "current_sign_in_ip" 
    t.string "last_sign_in_ip" 
    t.string "image_file_name" 
    t.string "image_content_type" 
    t.integer "image_file_size" 
    t.datetime "image_updated_at" 
    t.datetime "created_at", :null => false 
    t.datetime "updated_at", :null => false 
    t.string "username" 
    t.string "bio" 
    t.string "location" 
end 

end 
+0

只需遍历'@ user.teams',然后输出一个团队的'members'数量?你已经有了这些关联,你只需要使用它们。 – sevenseacat

+0

我同意@sevenseacat,如果您需要一些代码才能在视图中显示这些值,那么您需要通过适当的教程来了解如何执行此操作。 – jvnill

回答

0

你有这些关联,你只需要遍历视图中的团队。 E.g类似:

# users/show.html.erb 
... 
<% @user.teams.each do |team| %> 
<div><%= "#{team.name} (#{team.members.count})" %></div> 
<% end %> 
... 

根据您与团队和成员的数据做还有什么,出于性能的原因,可能是一个好主意,eager load一些与用户的关联。

+0

非常感谢您的热心指导! – TonyTau