Ruby on rails Rails创建具有嵌套属性的记录
我创建记录的RSpec测试失败 在我的收据课上Ruby on rails Rails创建具有嵌套属性的记录,ruby-on-rails,rspec,nested-attributes,Ruby On Rails,Rspec,Nested Attributes,我创建记录的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 val
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
接收控制器.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
我也尝试过这一强参数
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"}
它将保存收据,但不会通过rails服务器窗口中的accepts_nested_attributes_for:po_receipts保存po_收据,当您创建一个具有嵌套属性的收据时。。。您通常会看到一条消息,告诉您它不接受某些属性,并将它们丢弃。您能否尝试在浏览器中创建,并查看是否有任何错误消息表明这一点,并检查它是否接受那里的属性?谢谢@TarynEast的回复。它实际上是无声地失败的。我最终根据浏览器中的视图生成的结果生成了RSpec参数。这就是为什么它让我困惑的部分原因。rspec默默地失败了。。。但在浏览器窗口中尝试,同时查看服务器日志。看看哪些参数实际上以散列形式传递,然后将它们复制/粘贴到您的问题中。然后此外,还应复制紧随其后的任何一行,该行将参数视为不允许删除,如果您的参数未通过许可/要求行,则该行将100%始终出现在日志中。