【问题标题】:What's the best way to make a new model when overriding the Devise User Controller?覆盖设计用户控制器时制作新模型的最佳方法是什么?
【发布时间】:2017-05-06 22:50:59
【问题描述】:

我正在尝试这样做,以便在(通过设计)创建新用户时,如果不存在具有该名称的先前家庭模型,则将创建一个新的家庭(基本上是一个组)模型。

伪代码:

if Household.find(params[:household_name))
  # allow current_user to join household
else
 # create new Household model with User's household_name parameter
end

我已经用 controllers/registerhousehold_controller.rb 覆盖了来自 Devise::RegistrationsController 的基本用户控制器:

class RegisterhouseholdController < Devise::RegistrationsController

但我不确定如何在这里实现实际的创建。有什么建议吗?

【问题讨论】:

    标签: ruby-on-rails devise


    【解决方案1】:

    据我所知,不需要更改控制器。

    用户.rb

    after_create :create_or_join_to_household
    
    def create_or_join_to_household
     household = Household.find(params[:household_name])
     if household.present?
       self.join_to_household
     else
       Household.create(name: params[:household_name])
       #or self.households.create(name: params[:household_name])
       #if you have a household - user relation somehow
    end
    

    附言

    join_to_household 将是您的用户模型中的另一种方法,它将创建 household_users 关系。

    【讨论】:

    • 这正是我所需要的。非常感谢!
    【解决方案2】:

    简单 - 使用 user 模型中的 before_create 回调来构建对象,然后您就可以在保存时使用它:

    #app/models/user.rb
    Class User < ActiveRecord::Base
        before_create :set_household, if: Proc.new {|user| user.household_id.present? }
    
        private
    
        def set_household
            if house = Household.find(self.household_id)
               #if it is set
            else
               #create a new houshold
            end
        end
    end
    

    【讨论】:

      【解决方案3】:

      在成功注册后,我必须在之前的任务中调用自定义方法。 你也需要类似的东西。

      我不确定是否要覆盖。

      在应用程序中试试这个。控制器

      class ApplicationController < ActionController::Base
      
      def after_sign_in_path_for(resource)
       if Household.find(params[:household_name))
          # allow current_user to join household
       else
          #create new Household model with User's household_name parameter
       end
       root_path
      end
      
      end
      

      查看this

      【讨论】:

        猜你喜欢
        • 2011-06-09
        • 1970-01-01
        • 2011-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-30
        • 2011-12-17
        • 1970-01-01
        相关资源
        最近更新 更多