注册时在Devise User对象上创建关联记录的设计注意事项

时间:2011-06-19 16:22:25

标签: ruby-on-rails devise

我正在使用Devise,并且对于创建的每个用户帐户,我想要生成以下关系:

class User < ActiveRecord::Base
  belongs_to :business
end

class Business < ActiveRecord::Base
  has_many :users
  has_one :apt_setting
  has_many :hours, :as => :hourable
end

class ApptSetting < ActiveRecord::Base
  belongs_to :business  
end

因此,在注册时,会创建一个关联的Business对象,并且每个Business对象都会创建一个关联的ApptSettings和BusinessHour对象。

我目前的实现方式如下:

class Admin

  before_create :create_associated_records

    def create_associated_records
      # create the associated business object
    business = Business.create(:business_name => business_name, :subdomain => subdomain, :initial_plan => initial_plan)
    # retrieve the id of the new business object
    self.business_id = business.id

    # create the associated records
    BusinessHour.default_values(business_id)
    ApptSetting.default_values(business_id)
    end
end

class ApptSetting < ActiveRecord::Base
  belongs_to :business

  def self.default_values(business_id)
    # ... create record with default values
  end

end

class BusinessHour < Hour
  belongs_to :hourable, :polymorphic => true

  def self.default_values(business_id)
    # ... create record with default values
  end

end

这确实有效,但它看起来是最好的设计吗?

我正在考虑的一个替代方案是处理删除管理员 - &gt; create_associated_records,而是在Users :: Accounts :: RegistrationsController中执行该操作,其中我覆盖'create'方法。在那里,我可以构建所有相关的记录,在适当的地方设置:accepts_nested_attributes,然后在Business对象上调用'save',然后应该生成所有相关的记录。

关于最佳设计或任何其他想法的想法?

1 个答案:

答案 0 :(得分:2)

您不需要default_values方法。在create_associated_records中,您可以将这些调用更改为:

ApptSetting.create(:business_id => business_id)

不要覆盖create方法。 before_create回调是更好的方法。在任何一种情况下,如果企业有很多用户,您是否真的想在每次创建新用户时创建新业务?如何将第二个用户添加到企业中?添加类似的东西,

def create_associated_records
  return unless self.business_id.nil?
  ....

另外,您的方法中的business_name,subdomain和initial_plan变量在哪里?你有他们作为管理员用户的属性?似乎他们应该只是业务的价值。

我认为这里最大的问题是,用户真的是否需要一个企业才能存在?为什么用户在创建帐户后无法创建业务?

**编辑:使用rails关联方法更清晰/更清晰:

class Admin

  before_create :create_associated_records

  private

  def create_associated_records
    return unless self.business_id.nil?
    self.create_business
    self.business.create_appt_setting
    self.business.hours.create
  end

end