matiss matiss - 1 year ago 114
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 current_user)
if[:error] = "You can do whatever want!"
else[:error] = "Only view!"

In console I can get this: => 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" ( says "You can do whatever want!"
Please, any suggestions how to do this? Many thanks!

Answer Source

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

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download