Created
October 9, 2008 08:53
-
-
Save moro/15726 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ============= 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