7

I have a many-to-many relationship like this: A user has_many organizations through affiliations and vice-versa.

I'm using declarative organizations and I only want a user to edit a particular organization if he is affiliated and the affiliationtype attribute of affiliation is a particular value.

So affiliations has 3 columns , user_id, organization_id and affiliationtype_id

I can do:

o = Organization.find(:first)
o.affiliatons[0].user and get the user

now I wish to do this:

has_permission_on [:organizations], :to => :edit do
  if_attribute (...)
end

That if_attribute should see if the current user is the organization.affiliation[?].user and if the organization.affiliation[?].affiliationtype_id = "3"

I hope this is syntax issue ... I really need to get this working.

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Victor Martins
  • 1,355
  • 1
  • 12
  • 23

1 Answers1

7

EDIT:

You can restrict the type of affiliation with intersects_with(&block) :

  has_permission_on [:organizations], :to => :edit do
    if_attribute :affiliations => intersects_with {
      user.affiliations.with_type_3
    }
  end

Why not create a named_scope to find affiliations whose affiliationtype_id = 3?


From declarative_authorization documentation:

To reduce redundancy in has_permission_on blocks, a rule may depend on permissions on associated objects:

authorization do
  role :branch_admin do
    has_permission_on :branches, :to => :manage do
      if_attribute :managers => contains {user}
    end

    has_permission_on :employees, :to => :manage do
      if_permitted_to :manage, :branch
      # instead of
      #if_attribute :branch => {:managers => contains {user}}
    end
  end
end
nanda
  • 1,313
  • 9
  • 16
  • I can find the user and validate the match. But I need to find the user AND see if is affiliation has an affiliationtype of a certain id. I can get is user_id, but how do i see for the affiliationtype of that user_id? I don't get it... – Victor Martins Mar 13 '10 at 21:12
  • See my edit, I think this can help. There's only one or zero affiliation object that intersects with Organization.affiliations and user.affiliations.with_type_3 (named_scope suggestion). – nanda Mar 13 '10 at 21:51
  • almost... this works on the console giving me just one value for the user: v.affiliations.type_admin but the if_attribute :affiliations => intersects_with { user.affiliations.type_admin } Never validates true – Victor Martins Mar 13 '10 at 22:29
  • You added the named_scope to the Affiliation model? named_scope :type_admin, :conditions => {:affiliationtype_id => 3} – nanda Mar 13 '10 at 22:44
  • I've tried exactly the same thing but it hasn't worked for me... :/ Has the gem been updated at all? – digitalWestie Jun 06 '10 at 18:49
  • I love it. Thanks! I have a habtm relationship and the contains{user} block works nicely. – jspooner Aug 27 '10 at 22:22