Skip to content

Instantly share code, notes, and snippets.

@moro
Created October 9, 2008 08:53
Show Gist options
  • Save moro/15726 to your computer and use it in GitHub Desktop.
Save moro/15726 to your computer and use it in GitHub Desktop.
# ============= Definition ==============
class User < ActiveRecord::Base
has_many :memberships
def accessible(klass)
klass.scoped( :conditions=>[<<-SQL, klass.name, self] )
#{klass.table_name}.id IN (
SELECT a.accessible_id
FROM accessibilities AS a
JOIN memberships AS m ON a.role_id = m.role_id
WHERE a.accesible_type = ? AND m.user_id = ?
)
SQL
end
end
# ----------
class Membership < ActiveRecord::Base
belongs_to :role
belongs_to :user
end
# ----------
class Role < ActiveRecord::Base
has_many :memberships
has_many :accessibilities
end
# ----------
class Accessibility < ActiveRecord::Base
belongs_to :role
belongs_to :accessible, :polymorpihc => true
end
# ----------
class Item < ActiveRecord::Base
has_many :accessibilities, :as => :accessible
end
# ============= Example ==============
me = User.find_by_name("moro")
me.accessible(Item).find(:all, :order=>"updated_at DESC")
#=> [ <accessible items > ]
me.accessible(Item).find( 10 )
#=> If I can access Item(id=10), find it.
# else raises AR::RecordNotFound
# (and handle AR::RecordNotFound in controller to render 404
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment