【问题标题】:Rails call specific action on modelRails 对模型调用特定操作
【发布时间】:2013-12-11 21:41:53
【问题描述】:

我有一个这样的模型,例如:

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

所以Contact.new 会为type 生成一个具有nil 值的联系人,但“紫色联系人”会为type 创建一个具有purple 值的联系人,以及为@ 生成fishing 值的联系人987654334@.

【问题讨论】:

  • 为什么不在数据库中只有一种联系人类型,然后在执行 Contact.New(type) 时指定类型?
  • 基本上每个联系人都将具有相同的属性,只是值会根据 csv 文件中的内容而改变。我想我可以创建 15 种不同的联系模型,但创建一个具有 15 种不同“类型”的联系模型似乎更简洁。
  • 听起来您只想创建Contact 的子类。我对这个问题还有什么遗漏吗?
  • 不 - 你是对的。我想创建 Contact 的子类。

标签: ruby-on-rails ruby model controller


【解决方案1】:

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)

这将返回一个新的联系人实例,其中@type 设置为紫色。

【讨论】:

    【解决方案2】:

    使用继承。

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

    【讨论】:

    • 使用这个方法似乎唯一被定义的属性是type。我原来的 Contact 初始化方法中的所有值都没有被分配 - 关于如何在不一遍又一遍地写 super(attribute) 的情况下将其拉入的想法?
    • super 调用父级初始化方法,因此原始Contact 初始化中的值被分配
    • 有效 - 我只是犯了一个简单的错误。感谢您的提示。
    猜你喜欢
    • 1970-01-01
    • 2017-01-29
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    • 2023-04-04
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多