views:

27

answers:

2

Given the following model:

class User < AR::B 
  has_many :permissions 
  has_many :projects, :through => :permissions 
end 
class Project < AR::B 
  has_many :permissions 
  has_many :users, :through => :permissions 
end 
class Role < AR::B 
  has_many :permissions 
end 
class Permission < AR::B 
  belongs_to :user 
  belongs_to :project 
  belongs_to :role 
end

In the user.rb model,,, how can I obtain the user's permission for the project?

Something like self.permissions.role ?

Thanks!

+1  A: 

You could add an instance method to the User model that took the project as an argument and returned the permission.

class User < AR
  def permission_for_project(project)
    permissions.find_by_project_id(project.id)
  end

  def role_for_project(project)
    permission = permissions.find_by_project_id(project.id)

    permission.role unless permission.nil?
  end
end

Then use it like:

user = User.find(n)
project = Project.find(n)

permission = user.permission_for_project(project)

role = user.role_for_project(project)
Beerlington
Thanks, that's close but it isn't return the role.name from the Roles table. Here is the query from the log: "SELECT "permissions".* FROM "permissions" WHERE ("permissions".user_id = 1) AND ("permissions"."project_id" = 1) LIMIT 1" How can that be updated to return the user's role if any for that project? thxs!
AnApprentice
I updated it to add a method that returned the role for a project. If there's no permission, it will just return nil
Beerlington
This is great - thank you!
AnApprentice
Question, what does the find(n) do? I haven't seen that before...
AnApprentice
Beerlington has just used `n` to represent the id of the user of project you want to access. You might have `User.find(params[:id])` and `Project.find(params[:project_id])` for example.
Shadwell
+1  A: 
(the_role = user.permissions.find(:first, project_id => project_id).role) && 
   the_role.name

Should look up the (first) permission that the user has for that project and get the role. If there is a role then it will return the name, if not it will return nil.

Shadwell
Thanks Shadwell your answer was dead on.
AnApprentice