Question

I have a web application where I'm storing the type of users as a hash field. and i have many collections. what would be the best way to process that hash field.

class Community
  include Mongoid::Document

  class UserRoles
    Admin = :a
    Moderator = :m
  end

  include Mongoid::Timestamps

  field :un, as: :username, type: String
  field :nm, as: :name, type: String

  field :suids, as: :special_user_ids, type: Hash
  has_and_belongs_to_many :users
end

Now there can be many communities, having many users, and each user having many moderators. So for Special users i'm storing it as hash.

Now how would i compute if the current user who has logged in, is he a moderator/admin of any of the communities

I tried this and obviously this doesnt work. It'll work if i have a single document to deal with. And my solution doesnt serve the purpose of why the hash is used in first place.

  #  suids = []
  #  @communities = Community.all
  #  suids << @community.special_user_ids.collect { |k, v| k }
  #  //code doesnt find special_user_ids as it has too many documents to deal with.
  #  communities_path(@community.id)

I have a working code to find all the admins/moderator of a given community.

def admins
    @community = Community.find(params[:id])
    @users = User.where(:id.in => @community.special_user_ids.collect { |k, v| k })
end
Was it helpful?

Solution

For the desired communities get the admins, then you can do

if admins.include?(current_user)
    # treat as admin
end

Edit

all_admins = Array.new

Get all commmuniteis

@communities = Community.all

@communities.each do |c_comm|
   all_admins.concat(User.where(:id.in => c_comm.special_user_ids.collect { |k, v| k }))
end

puts all_admins.include(current_user)?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top