我有三个用户模型。用户,角色和分配。这就是模型的外观:
assignment.rb
# == Schema Information
# Schema version: 20101117094659
#
# Table name: assignments
#
# id :integer not null, primary key
# created_at :datetime
# updated_at :datetime
# user_id :integer
# role_id :integer
#
class Assignment < ActiveRecord::Base
belongs_to :role
belongs_to :user
end
role.rb
# == Schema Information
# Schema version: 20101117094659
#
# Table name: roles
#
# id :integer not null, primary key
# name :string(255)
# created_at :datetime
# updated_at :datetime
#
class Role < ActiveRecord::Base
has_many :assignments
has_many :users, :through => :assignments
end
user.rb
# == Schema Information
# Schema version: 20110102225945
#
# Table name: users
#
# id :integer primary key
# email :string(255)
# encrypted_password :string(128)
# password_salt :string(255)
# reset_password_token :string(255)
# remember_token :string(255)
# remember_created_at :datetime
# sign_in_count :integer
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string(255)
# last_sign_in_ip :string(255)
# created_at :datetime
# updated_at :datetime
# username :string(255)
# f_name :string(255)
# l_name :string(255)
#
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, and :lockable
devise :database_authenticatable, :registerable, :timeoutable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
has_and_belongs_to_many :projects
has_many :stages
has_many :uploads
has_many :comments
has_many :assignments
has_many :roles, :through => :assignments
def role_symbols
roles.map do |role|
role.name.underscore.to_sym
end
end
end
在我看来,要为当前用户选择项目,我这样做:
在我的项目控制器中,我有:
def index
@projects = current_user.projects
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @projects }
end
端
然后在视图中我这样做:
<% if current_user.projects.exists? %>
<div class="data">
There are <%= current_user.projects.count %> projects.<br />
<table>
<% current_user.projects.each do |project| %>
<tr class="changer">
<td><%= link_to project.name, project %></td>
</tr>
<% end %>
</table>
</div>
<% else %>
<div class="no-data">
<%= image_tag('create-project-icon.png') %><br />
Create Project
</div>
<% end %>
用户有4个角色:Designer,Client,Admin,Superuser。
每个设计师可以拥有多个客户。每个客户也可以属于多个设计师。
所以我猜我有两个问题:
感谢。
答案 0 :(得分:0)
问题是......鉴于已经添加了用户(客户端) 到另一个用户(设计师)拥有的项目,我该如何检索 那些用户
这很简单:
# Given a project @project = Project.find(id)
@clients = @project.users.joins(:roles).where("roles.name = 'client'")