0

环境:

CentOS-6.7 / OSX-10.9.5
Ruby 2.2.3p173 (probably time for an update)
Rails 4.2.5.1
Trailblazer 1.1.0

我正在完成开拓者书中的练习,并尝试将现有项目的元素映射到书中的示例。在手头的项目中,我们使用 AR 继承为单个下级表创建模型别名。下面给出一个例子:

class ARAccount< GLAccount
  after_initialize( :set_sub_ledger,  { :if => :new_record? } )
  has_one(  :active_client,
            -> { where IsActiveRow },
            :class_name => 'ARClient',
            :dependent => :restrict_with_error,
            :foreign_key => :gl_account_id
         )

  def gl_sub_ledger=( code )  # No change to sub_ledger value allowed
     gl_sub_ledger ||= AR_SUB_LEDGER   # Return 'AR' if not saved
  end

  private

  def set_sub_ledger          # set fixed value for AR sub_ledger
    write_attribute( :gl_sub_ledger, AR_SUB_LEDGER ) if new_record?
  end

  self.inheritance_column = :gl_ledger
  def sti_name
    "ASST"
  end
end

这种工作方式是从单表继承中借用的,因为每个变体模型定义的列值是“固定的”,但所有变体的基础表和行都是相同的。

我对如何operation.rb在 ar_invoice 关注的文件中处理这件事感到有些困惑。这个 AR 设置是在与 AR 处理继承的一些斗争之后演变而来的,所以我对使用 Trailblazer 演示的更简单的方法非常感兴趣。

4

1 回答 1

2

迟了一年的答复。

这是ARAccount::Create操作。

class ARAccount::Create < Trailblazer::Operation
  step Model( ARAccount, :new ) # this creates a new model for you.
  step :set_sub_ledger
  step # ... whatever you need after that.

  def set_sub_ledger(options, model:, **) # set fixed value for AR sub_ledger
    model.write_attribute( :gl_sub_ledger, AR_SUB_LEDGER )
  end
end

由于您进行了此if new_record?检查,因此您不需要set_sub_ledgerUpdate.

class ARAccount::Update < Trailblazer::Operation
  step Model( ARAccount, :find ) # this finds an existing model for you.
  step # ... whatever you need after that.
end

这个模型现在很苗条。

class ARAccount< GLAccount
  has_one(  :active_client,
        -> { where IsActiveRow },
        :class_name => 'ARClient',
        :dependent => :restrict_with_error,
        :foreign_key => :gl_account_id
     )

  self.inheritance_column = :gl_ledger
  def sti_name
    "ASST"
  end
end

Query在引入对象之前,您通常会在模型中保留范围和查找器。

于 2017-02-03T14:59:14.433 回答