0

以下问答基于 Trailblazer book pp. ~50-60 中给出的示例,适用于我的具体要求。如果按照书中的说明进行操作,您可以简单地将ARInvoicear_invoice视为Thing并获得一般漂移。thing

我的operation.rb文件是:

class ARInvoice < GLTransaction   class Create <
  Trailblazer::Operation

    include( Model )
    model( ARInvoice, :create )

    contract() do
      property( :invoice_number )
      property( :currency_code )
      property( :forex_rate )
      property( :gl_account_id )

      validates( :invoice_number, :presence => true )
      validates( :currency_code, :presence => true )
    end

    def process( params )
      @model = ARInvoice.new  # have to use instance variable here
      validate( params[ :ar_invoice ], @model ) do |f|
        f.save
      end
    end
  end
end

我从开拓者的书中改编了这个测试:

it("INSERTs a valid invoice") do
  test_time = Time.now
  puts(test_time)
  ar_invoice = ARInvoice::Create.(
    :ar_invoice => {
      :invoice_number => 101,
      :gl_account_id => 1,
      :effective_from => test_time.to_s
    }
  ).model

  ar_invoice.persisted?.must_equal(true)
  ar_invoice.invoice_number.must_equal(101)
  ar_invoice.transaction_type.must_equal('IN')
  ar_invoice.effective_from.must_equal(test_time)
  ar_invoice.superseded_after.must_equal(nil)
end

我得到了这个错误:

ar_invoice crud Create#test_0001_INSERTs a valid invoice: \
ActiveRecord::StatementInvalid: SQLite3::ConstraintException: \
gl_transactions.effective_from may not be NULL: \
INSERT INTO "gl_transactions" . . .

但我也看到了这个:

# Running:
2016-02-08 11:24:35 -0500
E

因此,设置了 test_time 值。为什么它没有进入effective_from属性?

我在下面给出的答案。

4

1 回答 1

0

问题是我没有掌握contract do/endTrailblazer (TBR) 中使用的块的重要性。我最初阅读这本书的方式是合同与表格有关。我在 RoR 方面的经验使我将单词形式与单词视图映射在一起。我的错。但也可能会绊倒其他人。

正确的合约块包含缺失的属性:effective_from

contract() do
  property( :invoice_number )
  property( :currency_code )
  property( :forex_rate )
  property( :gl_account_id )

  property( :effective_from )

  validates( :invoice_number, :presence => true )
  validates( :currency_code, :presence => true )
end

现在,如果我将这个词映射formparams[ :model ]. params[ :model ]因为调用方法时在哈希中查找的属性process仅限于在contract do/end块中显式列出的那些属性;这就是使用 TBR 时不需要强参数的原因

请注意,原始测试仍然失败,因为currency_code未满足验证。但这在编写此测试时是有意的。

于 2016-02-08T18:23:46.223 回答