ruby-on-rails - 这是一个已知的 Rails Manager 模式吗

标签 ruby-on-rails

我正在浏览一个同事的代码,但找不到一个使用过它的教程。有人可以指出一些使用过它的资源吗?这使代码非常干净,但我还没有找到任何引用。这只是本类(class)的一部分。它包括其他一些更多的方法。

class Manager
        include ActiveModel::Model
        include ActiveModel::Associations

      attr_accessor :application_id, :user_id, :user_application_id,.........
      belongs_to :application
      belongs_to :user_application
      belongs_to :user .. more belongs .......

       # This method is necessary to enable this ActiveModel Class to be used in views along with Form helpers
      def self._reflect_on_association(association) #:nodoc:
       _reflections[association.to_sym]
      end

      def []=(attr, value)
        self.send("#{attr}=", value)
      end

      def [](attr)
        multi_attribute_ids = [:some_ids.to_s, :someid2.to_s]
        return if multi_attribute_ids.include?(attr)
        self.send(attr)
      end
      def applicant_name 
      end
      -- some more methods
end

这样的“经理”有什么用。在这里使用 self.send 的两种方法是什么。这是 Rails 中的常见模式吗?

最佳答案

是的,随着 Rails 3 中 ActiveModel 的引入,使用域对象(在本例中称为管理器)已成为一种越来越普遍的模式,这些域对象不受实际数据库表的支持,但看起来和感觉起来都像模型。

即使 ActiveModel 做到了 particularly convenient挑选并选择 Rails 模型功能以合并到任意类中,这种模式是 Rails 先驱的东西 have been encouraging很久以来。

正如您发布的示例中清楚说明的那样,这种模式允许我们定义虚拟模型和虚拟关联,它们可以轻松利用表单助手和假设模型对象编写的其他 Rails 细节。

关于ruby-on-rails - 这是一个已知的 Rails Manager 模式吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40011663/

相关文章:

ruby-on-rails - Rails 3.2,如何更改:from value in a mailer instead default (GMail)

javascript - 添加新路径后图像不显示

ruby-on-rails - 设计确认链接缺少域

ruby-on-rails - 如何在 Rails 4 中使用 params.require

ruby-on-rails - 编写 gem 时需要源文件的最佳方法是什么

ruby-on-rails - 如何按时间在 rails 中订购多个 ActiveRecords?

javascript - 如何禁用特定页面上的js脚本?

ruby-on-rails - 更改选择框时的动态嵌套表单

ruby-on-rails - 如何知道模型何时被 :dependent => :destroy in rails? 自动销毁

mysql - 如何在 FreeBSD 上检查 mysql 状态?