2011-06-19 115 views
1

在设计用户对象创建相关的记录我使用的设计,并为创建的每个用户帐户,我想生成一个关系,其中:设计考虑上注册

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 

所以在登记相关的业务对象创建,并且每个业务对象都会创建一个关联的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 

这并不工作,但它似乎是最好的设计?

一种选择,我考虑的是处理消除管理 - > create_associated_records,而是做用户的工作::账户:: RegistrationsController,我重写“create”方法。在那里我可以建立所有关联的记录,在适当的地方设置:accepting_nested_attributes,然后在Business对象上调用'save',这会导致生成所有关联的记录。

思考的最佳设计,或任何其他的想法?

回答

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 
+0

还,什么是这方面的一个ApptSetting?是预约设置?像时间?一个企业真的只有一次的约会? – MissingHandle

+0

1),所以如果我删除default_values我可以只默认值初始化,而不必直接调用它,对吗? 2)我计划处理用户在此之后注册添加到现有企业帐户的情况。但就目前而言,我正在考虑创建最初的企业帐户,它必须至少有一个用户。在这种情况下,他们应该同时创建,所以是的,一个企业必须存在于用户之前。 3)ApptSettings不是时候,而是像定制的消息。 – 99miles

+0

哦,我明白了,我会打电话给before_create before_save的设置默认值 – 99miles