我创建记录的RSpec测试失败。
在我的收据课......
class Receipt < ActiveRecord::Base
has_many :po_receipts, dependent: :restrict_with_exception
has_many :jobquote_orders, through: :po_receipts
validates_presence_of :receipt
validates_presence_of :receipt_date
validates_uniqueness_of :receipt, scope: :receipt_date, message: 'That receipt already exists.'
accepts_nested_attributes_for :po_receipts
end
receipts_controller_spec.rb
receipt1 = Fabricate.attributes_for(:receipt)
receipt1[:po_receipts_attributes] = {1 => {qty: 25, jobquote_order_id: 1}, 2 => {qty: 30, jobquote_order_id: 2}}
post :create, receipt: receipt1
expect(PoReceipt.count).to eq(2)
receipts_controller.rb
def new
@receipt = Receipt.new
end
def create
@receipt = Receipt.new(receipt_params)
if is_user_or_admin?
if @receipt.save
flash[:success] = "Receipt created."
redirect_to receipts_path
else
flash[:warning] = "Invalid data."
render :new
end
else
flash[:danger] = "You are not authorized to do that."
redirect_to receipts_path
end
end
private
def receipt_params
params.require(:receipt).permit(:receipt, :receipt_date, po_receipts_attributes: [:qty, :jobquote_order_id])
end
我也尝试过这个强大的参数......
def receipt_params
params.require(:receipt).permit(:receipt, :receipt_date, po_receipts_attributes: [])
end
我也尝试过这个强大的参数...
def receipt_params
params.require(:receipt).permit(:receipt, :receipt_date).tap do |t|
t[:po_receipts_attributes] = params[:receipt][:po_receipts_attributes]
end
end
以下是从规范(和视图)传递的参数......
pry(#<ReceiptsController>)> params
=> {"receipt"=>
{"receipt"=>"3cufkz",
"receipt_date"=>"01/09/2014",
"po_receipts_attributes"=>
{0=>{"qty"=>"25", "jobquote_order_id"=>"1"},
1=>{"qty"=>"30", "jobquote_order_id"=>"2"}}},
"controller"=>"receipts",
"action"=>"create"}
它会保存收据,但不会通过accepts_nested_attributes_for :po_receipts