Skip to content

Instantly share code, notes, and snippets.

@EppO
Forked from mauriciopasquier/gist:4225871
Created December 6, 2012 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EppO/4227865 to your computer and use it in GitHub Desktop.
Save EppO/4227865 to your computer and use it in GitHub Desktop.
rolify
# User model
class Usuario < ActiveRecord::Base
rolify :role_cname => 'Rol'
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
# attr_accessible :title, :body
end
# Role model
class Rol < ActiveRecord::Base
has_and_belongs_to_many :usuarios, :join_table => :usuarios_rols
belongs_to :resource, :polymorphic => true
scopify
end
irb(main):010:0> u
=> #<Usuario id: 1, email: "anyemailuwant@bla.com", encrypted_password: "$2a$10$iBJWUyl/4MLOm4zbKMQ2Y.1NTDo9gwLJg9IMnGFhg50x...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: "2012-12-06 20:06:46", updated_at: "2012-12-06 20:06:46">
irb(main):009:0> u.add_role :admin
Rol Load (0.2ms) SELECT "rols".* FROM "rols" WHERE "rols"."name" = 'admin' AND "rols"."resource_type" IS NULL AND "rols"."resource_id" IS NULL LIMIT 1
(0.1ms) begin transaction
SQL (0.7ms) INSERT INTO "rols" ("created_at", "name", "resource_id", "resource_type", "updated_at") VALUES (?, ?, ?, ?, ?) [["created_at", Thu, 06 Dec 2012 20:07:04 UTC +00:00], ["name", "admin"], ["resource_id", nil], ["resource_type", nil], ["updated_at", Thu, 06 Dec 2012 20:07:04 UTC +00:00]]
(1.4ms) commit transaction
Rol Load (0.2ms) SELECT "rols".* FROM "rols" WHERE "rols"."id" = ? LIMIT 1 [["id", 1]]
(0.0ms) begin transaction
(0.3ms) INSERT INTO "usuarios_rols" ("usuario_id", "rol_id") VALUES (1, 1)
(1.0ms) commit transaction
=> #<Rol id: 1, name: "admin", resource_id: nil, resource_type: nil, created_at: "2012-12-06 20:07:04", updated_at: "2012-12-06 20:07:04">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment