以下Q& A基于Trailblazer书籍pp .~50-60中给出的示例,根据我的具体要求进行了调整。您可以简单地将ARInvoice
和ar_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
属性?
我在下面给出的答案。
答案 0 :(得分:0)
问题在于我没有理解Trailblazer(TBR)中使用的contract
do/end
块的重要性。我最初阅读这本书的方式是合同与表格有关。我对RoR的经验使我将单词 form 映射到 view 。我的错。但也可能会绊倒其他人。
正确的合约区块包含缺少的属性: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
目前,如果我将单词form
映射到params[ :model ]
,它会对我有所帮助。因为调用params[ :model ]
方法时在process
哈希中查找的属性仅限于contract
do/end
块中明确列出的那些属性; 这就是使用TBR 时不需要强参数的原因。
请注意,原始测试仍然失败,因为未满足currency_code
验证。但是在编写本测试时,这是故意的。