【问题标题】:Does Devise work only with STI models?Devise 是否仅适用于 STI 模型?
【发布时间】:2023-03-25 08:05:01
【问题描述】:

当您尝试自定义其行为时,我无法理解设计的工作原理。

我有两种不同的模型需要处理:SocietyCollaborator,并且它们的注册表必须在相同的视图中。
所以我必须重写“设计注册控制器创建方法”,编写一个新的控制器来处理这两个模型。

痛苦来了。
从这里“Devise form within a different controller”和here,我知道我必须定义那些新的助手,才能使设计工作:

module ContentHelper
  def resource_name
    :user
  end

  def resource
    @resource ||= User.new
  end

  def devise_mapping
    @devise_mapping ||= Devise.mappings[:user]
  end
end

我要重写的创建方法是这样的:

def create
build_resource

if resource.save
  if resource.active_for_authentication?
    set_flash_message :notice, :signed_up if is_navigational_format?
    sign_in(resource_name, resource)
    respond_with resource, :location => after_sign_up_path_for(resource)
  else
    set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
    expire_session_data_after_sign_in!
    respond_with resource, :location => after_inactive_sign_up_path_for(resource)
  end
else
  clean_up_passwords resource
  respond_with resource
end

结束

我不知道如何在不影响守望者功能的情况下使其工作。 (构建资源)。有什么建议吗?我找不到任何不使用 STI 的解决方案!

【问题讨论】:

    标签: ruby-on-rails controller devise helper


    【解决方案1】:

    听起来您将有一个复杂的模型设置,这可能会困扰您。如果您需要两个不同的“用户”模型,也许您仍然可以拥有一个用户模型,然后还拥有每个“has_one :user”的 Society 和 Collaborator 模型。这样,在注册时,您就可以创建用户记录,以及 Society 或 Collaborator 方法(无论选择哪一个)。这样设计(以及您的所有身份验证)只是链接到用户模型并且它保持简单。

    一般来说,如果您发现自己在与谷物作斗争,那么重新评估您正在做的事情是个好主意。除非您正在做一些开创性的事情,否则事情很可能不会那么困难。

    【讨论】:

      【解决方案2】:

      你可以在devise的所有视图中定义变量,例如

      @type = :society
      

      def resource_name
          @type
      end
      

      然后你可以使用原来的控制器和视图,只需将其添加到 AplicationHelper 中

      PD:对于 User.new,您可以在 eval 条件中使用字符串,例如

      @res = "Society"
      

      然后

      @resource ||= eval(@res).new
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-30
        相关资源
        最近更新 更多