Rails 5:检查控制器中返回的枚举值

时间:2016-10-01 17:32:10

标签: ruby-on-rails ruby enums

我正在努力检查返回的枚举值。 在models / roles.rb中我有枚举:

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

在controllers / dashboard_controller.rb中我有:

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

在控制台中我可以得到这个:

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">]>` 

仪表板:“删除器”是我想要的结果。 我想检查控制器,如果仪表板的用户角色是“删除者”(flash.now说“你可以做任何想做的事!”

请提出任何建议如何做到这一点?非常感谢!

更新

这是我的controllers / dashboard_controller.rb

def dashboard_1
  @roles = current_user.roles
    if @roles.any? { |role| role.deleter_dashboard? }
      flash.now[:error] = "You are deleter!"
    elsif @roles.any? { |role| role.viewer_dashboard? }
      flash.now[:error] = "You are viewer!"
    else 
      redirect_to users_path
    end
  end

在dashboard_1.html.erb中,只有当用户为“信息中心”部分的“删除者”时,我才会尝试显示“新广告系列”按钮:

<% if @roles.deleter_dashboard? %>
   <%= link_to new_campaign_path(@campaign), {method: 'get', class: 'btn btn-w-m btn-primary'} do %>New campaign
   <% end %>
<% end %>

但是我一直收到这个错误 - 未定义方法deleter_dashboard? for Role :: ActiveRecord_Associations_CollectionProxy 如何让它正常工作?

1 个答案:

答案 0 :(得分:0)

也许您可以使用已初始化的实例变量@roles

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

根据documentation of Enum

,您应该可以role.deleter_dashboard?