我有一个这样的模型,例如:
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
然后,在我的 Controller 中,我想根据 csv 文件是否具有特定值作为属性来创建不同“类型”的 Contact
模型。
例如:
我知道我可以在 Controller 中调用 Contact.new
并毫无问题地创建 Contact
。我该如何调用类似 Purple_Contact.new
的内容?我希望初始化方法中的所有内容都能发生,但我希望某些联系人的 type
为 purple
。
因此,Contact.new
将生成一个 type
值为 nil
的联系人,但“Purple Contact”将创建一个具有类型
的紫色
值以及兴趣
的钓鱼
值。
最佳答案
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)
这将返回一个新的 Contact 实例,@type 设置为紫色。
关于ruby-on-rails - Rails 调用模型上的特定操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20530504/