繁体   English   中英

Rails调用模型上的特定操作

[英]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方法中的所有事情都发生,但我希望某些联系人也具有purpletype

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

Purple_Contact.newContact是不同的类,因此,就其本身而言,这种方式是行不通的。

您可以做的是:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM