Rails在模型上调用特定的操作

时间:2013-12-11 21:41:53

标签: ruby-on-rails ruby model controller

我有这样的模型,例如:

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之类的东西?我希望初始化方法中的所有内容都能发生,但我希望某些联系人也有type purple

因此Contact.new会产生nil的{​​{1}}值的联系人,但“紫色联系人”会为{{1}创建type值的联系人} {}以及purple的{​​{1}}。

2 个答案:

答案 0 :(得分:2)

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。

答案 1 :(得分:1)

使用继承。

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