2

我已经通过以下方式声明了 user_decorator.rb 而不是 user_helper.rb

class UserDecorator < Draper::Decorator
   delegate_all

  def contract_type
    contract_types.keys.collect {|k| [k.humanize, k]}
  end
  def employee_type
    employee_types.keys.collect {|k| [k.humanize, k]}
  end

  def department_role
    department_roles.keys.collect {|k| [k.humanize, k]}
  end
end

这是我在 user.rb 上声明的枚举

 enum contract_type: [:probationary, :apprenticeship, :six_months_to_one_year,
    :three_years]
  enum department_role: [:ceo, :cto, :coo, :manager, :tl, :gl, :developer]
  enum employee_type: [:full_time, :part_time, :internship]

我想从与注册控制器相关的视图中调用辅助方法。它就像

class RegistrationsController < Devise::RegistrationsController

  def new
    super
  end

  def create
    super
  end
end

但是,如果我调用辅助方法,例如从 views/devise/registrations/new.html.erb

<%= f.select :contract_type, contract_type, {prompt: t(".contract_type",
      default: "Select contract type")} %>

它没有找到contract_type。需要有关如何从 user_decorator.rb 上声明的视图访问辅助方法的帮助

4

2 回答 2

0

为了从 Devise 的current_user方法中获取修饰的用户对象,您可以覆盖它

class ApplicationController < ActionController::Base
  def current_user
    UserDecorator.decorate(super) unless super.nil?
  end
end

但是,由于您的问题在devise/registrations/new.html.erb页面上,此时用户不会登录,因此不会有任何类型的装饰current_user对象。

所以,看起来你想要的是从你的User模型中获取一组修饰的契约类型到那个视图中,你可以通过在控制器上创建一个实例变量来做到这一点:

class RegistrationsController < Devise::RegistrationsController
  def new
    @contract_types = User.contract_types.keys.collect {|k| [k.humanize, k]}
    super
  end
end

然后在视图中使用它:

<%= f.select :contract_type, 
             @contract_types,
             { prompt: t(".contract_type", default: "Select contract type") } %>

如果你想做进一步的重构,你也许可以在你的User模型上创建一个类似作用域的类方法来装饰契约类型:

class User < ActiveRecord::Base
  def self.humanized_contract_types
    contract_types.keys.collect {|k| [k.humanize, k]}
  end
end

因此,您的控制器代码可以缩短为:

class RegistrationsController < Devise::RegistrationsController
  def new
    @contract_types = User.humanized_contract_types
    super
  end
end

或者,如果您打算使用UserDecorator该类,您可以查看代理类方法调用它

于 2016-07-26T13:10:10.780 回答
0

您可以覆盖您的new方法来装饰您的资源,如下所示:

# registrations_controller.rb

def new
  build_resource({})
  yield resource if block_given?
  respond_with resource
end

protected

def build_resource(hash = nil)
  self.resource = resource_class.new_with_session(hash || {}, session).decorate
end
于 2017-10-03T12:31:12.310 回答