matiss matiss - 2 months ago 18
Ruby Question

Rails 5: Check returned enum value in controller

I am struggling to check returned enum value.
In models/roles.rb I have enums:

class Role < ApplicationRecord
belongs_to :user, optional: true
accepts_nested_attributes_for :user

enum general: { seller: 1, buyer: 2, seller_buyer: 3}, _suffix: true
enum dashboard: { denied: 0, viewer: 1, editer: 2, creater: 3, deleter: 4}, _suffix: true


In controllers/dashboard_controller.rb I have this:

class DashboardsController < ApplicationController
def dashboard_1
@roles = current_user.roles
Role.select(:dashboard).where(user_id: current_user)
if
flash.now[:error] = "You can do whatever want!"
else
flash.now[:error] = "Only view!"
end
end


In console I can get this:

Role.select(:dashboard).where(:user_id => 1)
Role Load (0.3ms) SELECT "roles"."dashboard" FROM "roles" WHERE "roles"."user_id" = ? [["user_id", 1]]`=> #<ActiveRecord::Relation [#<Role id: nil, dashboard: "deleter">]>`


where dashboard: "deleter" is my desired outcome.
I want to check in controller that if user role for dashboard is "deleter" (flash.now says "You can do whatever want!"
Please, any suggestions how to do this? Many thanks!

Answer

Maybe you could just use the instance variable @roles that you've initialized

if @roles.any? { |role| role.deleter_dashboard? }
  flash.now[:error] = "You can do whatever want!"
else 
  flash.now[:error] = "Only view!"
end

You should be able to role.deleter_dashboard? according to the documentation of Enum