Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 一次性保存父对象与多态子对象的关联时出错_Ruby_Ruby On Rails 3_Activerecord_Nested Attributes_Polymorphic Associations - Fatal编程技术网

Ruby 一次性保存父对象与多态子对象的关联时出错

Ruby 一次性保存父对象与多态子对象的关联时出错,ruby,ruby-on-rails-3,activerecord,nested-attributes,polymorphic-associations,Ruby,Ruby On Rails 3,Activerecord,Nested Attributes,Polymorphic Associations,我正在尝试一次性保存父对象(报表)和关联的多态子对象(附件)——关联是“has_one” 我正在对包含子级嵌套内容的params散列的报表使用“.create”方法,但收到错误“Validation failed:attachable attachable不能为空” 我所拥有的是(简单化): 父模型: Class Report has_one :attachment, as: :attachable, :dependent => :destroy attr_accessible

我正在尝试一次性保存父对象(报表)和关联的多态子对象(附件)——关联是“has_one”

我正在对包含子级嵌套内容的params散列的报表使用“.create”方法,但收到错误“Validation failed:attachable attachable不能为空”

我所拥有的是(简单化):

父模型:

Class Report
  has_one :attachment, as: :attachable, :dependent => :destroy

  attr_accessible :refdate, :link_name, :type_name, :attachment_attributes

  accepts_nested_attributes_for :attachment
子模型:

Class Attachment
  belongs_to :attachable, polymorphic: true

  attr_accessible :file

  validates_presence_of :attachable
  validates_presence_of :file
控制器:

ReportsController
  def create
    @report = Report.create!(params[:report])
  end
视图(haml):

通过调整控制器,我可以实现先将父级保存到db,然后保存附件(此处
attachable
由Rails自动填充),但我希望避免这种两步保存过程,以确保两者都保存,或者两者都不保存

有人有主意吗

谢谢

= form_for @report, html: { multipart: true } do |f|
  = f.select :type_name
  = f.text_field :link_name
  = f.text_field :refdate
  = f.fields_for :attachment_attributes, html: { multipart: true } do |p|
    = p.file_field :file
  = f.submit