在查看用户的“显示”页面时,我想显示用户所在的团队,然后显示每个团队的成员数量。我试图了解如何在模型中编写方法来实现此功能。
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 :(得分:0)
您已经建立了关联,您只需要在视图中迭代团队。例如:
# users/show.html.erb
...
<% @user.teams.each do |team| %>
<div><%= "#{team.name} (#{team.members.count})" %></div>
<% end %>
...
根据您对团队和成员数据的其他操作,出于性能原因,eager load与用户的某些关联可能是个好主意。