ruby on rails - Filtering archives with access groups with cancancan -
the user log in , able access archive if group user can view archive. archive can viewed many groups. groups , users compose them, determined administrator. how see if logged in user can see archive?
i'm using cancancan gem use skill, tried filter this:
can :read, archive, group: {id: user.group_ids} can :read, archive, group: {archive.joins(:groups).ids} can :read, archive, id: {archive.joins(:groups).ids} can :read, archive, id => {archive.joins(:groups).ids} can :read, archive, :id => {archive.where(group_user:(id: user.group_ids).pluck(:id))} can :read, archive, :group_users {:id => user.group_user_ids } module ability can :read, archive |a| a.archive_group.include?(user.archive_group) end end but none of above succeeded.
my schema:
create_table "archives", force: :cascade |t| t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "archives_groups", id: false, force: :cascade |t| t.integer "archive_id", null: false t.integer "group_id", null: false end create_table "groups", force: :cascade |t| t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "groups_users", id: false, force: :cascade |t| t.integer "group_id", null: false t.integer "user_id", null: false end create_table "users", force: :cascade |t| t.string "name" t.integer "kind" t.datetime "created_at", null: false t.datetime "updated_at", null: false end models:
class user < activerecord::base # include default devise modules. others available are: # :confirmable, :lockable, :timeoutable , :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable enum kind: [:admin, :user] has_and_belongs_to_many :groups end class group < activerecord::base has_and_belongs_to_many :users has_and_belongs_to_many :archives end class archive < activerecord::base has_and_belongs_to_many :groups end
for ability.rb can use if , call methods model (user)
class ability include cancan::ability def initialize(user) if user can :read, archive if user.has_group_membership?(:id) end end end inside user.rb, create method archive_id params, compare loop if user group ids archive id
def has_group_membership?(archive_id) token = false @archive = archive.find(archive_id) self.groups.each |group| # loop group user has @archive.groups.each |ar_group| # loop group archive has if group.name.to_sym == ar_group.name.to_sym # compare symbol (faster string) token = true break end end end return token end
Comments
Post a Comment