ruby-on-rails - Rails 调用模型上的特定操作

标签 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

然后,在我的 Controller 中,我想根据 csv 文件是否具有特定值作为属性来创建不同“类型”的 Contact 模型。

例如:

我知道我可以在 Controller 中调用 Contact.new 并毫无问题地创建 Contact。我该如何调用类似 Purple_Contact.new 的内容?我希望初始化方法中的所有内容都能发生,但我希望某些联系人的 typepurple

因此,Contact.new 将生成一个 type 值为 nil 的联系人,但“Purple Contact”将创建一个具有类型紫色值以及兴趣钓鱼值。

最佳答案

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 设置为紫色。

关于ruby-on-rails - Rails 调用模型上的特定操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20530504/

相关文章:

ruby-on-rails - 使用 Resque 重新排队作业

ruby - gem 命令。这意味着什么

ruby - 为什么不大写!方法在字符串上工作?

database - 将 n-gram 存储在数据库中 < n 个表中

memory - 小内存模型和大内存模型有什么区别?

java - 是否存在与 Java 的 Wicket 等效的 Ruby?

ruby-on-rails - Rails 4 SQLite3::SQLException 错误

ruby-on-rails - ruby on rails 基础帮助

ruby-on-rails - JSON 包含条件

php - 在事件记录中使用连接时如何选择特定列