[英]Rails call specific action on model
我有一个这样的模型,例如:
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
东西? 我希望我的initialize方法中的所有事情都发生,但我希望某些联系人也具有purple
的type
。
所以Contact.new
会产生与接触nil
为价值type
,而是一个“紫联系”将创建一个联系人purple
的价值type
以及fishing
的interests
。
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设置为Purple。
使用继承。
class PurpleContact < Contact
def initialize
super
@type = 'purple'
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.