2013-12-11 55 views
2

具体行动我有一个这样的模型,例如:Rails的呼吁模型

class Contact 
    include ActiveModel::Model 
    attr_reader :interests, :last_list_name, :type 

    def initialize() 
    @interests = 'fishing' 
    @last_list_name = 'last_list' 
    end 

    def purple_contact 
    @type = 'purple' 
    end 
end 

然后,在我的控制,我想根据是否从一个CSV文件中创建不同的Contact模型“类型”或者他们没有一定的价值作为属性。

例如:

我知道我可以打电话给我的控制器Contact.new并没有问题创造Contact。我将如何调用像Purple_Contact.new?我希望在初始化方法中发生所有事情,但我希望某些联系人也有typepurple

所以Contact.new会产生与type一个nil值接触,但“紫联系”将创建与type以及fishinginterests一个purple值的联系人。

+0

为什么不只是在数据库中有一种联系方式,那么当你做Contact.New(type)时,你可以指定类型? –

+0

基本上每个联系人都会具有相同的属性,只是值会根据在csv文件中看到的内容而改变。我想我可以创建15个不同的联系人模型,但创建一个包含15个不同“类型”的联系人模型似乎更加清晰。 – Luigi

+0

听起来好像你只是想创建Contact的子类。我是否错过了更多这个问题? – Jonah

回答

1

使用继承。

class PurpleContact < Contact 
    def initialize 
    super 
    @type = 'purple' 
    end 
end 
+0

使用这种方法,似乎只有定义的属性是'type'。我最初的'Contact'初始化方法中的所有值都没有被赋值 - 关于如何在不写'super(属性)'的情况下如何实现这一点的想法? – Luigi

+0

'super'调用父初始化方法,所以原来的'Contact'初始化中的值被赋值 – dotpao

+0

有效 - 我只是犯了一个简单的错误。感谢您的提示。 – Luigi

2

Purple_Contact.new将与Contact不同,所以它不会以这种方式工作。

你可以做的是:

class Contact 
    include ActiveModel::Model 
    attr_reader :interests, :last_list_name, :type 

    def initialize() 
    @interests = 'fishing' 
    @last_list_name = 'last_last' 
    end 

    def self.purple(new_args = {}) 
    new_args[type] = 'purple' 
    self.new(*new_args) 
    end 
end 

这将让你做这样的事情:

Contact.purple(initialization_hash) 

这将与@type设置为紫色返回联系的新实例。