3

親オブジェクト (レポート) と関連するポリモーフィックな子 (添付ファイル) を一度に保存しようとしています。関連付けは「has_one」です。

子のネストされたコンテンツを含む params ハッシュを含むレポートで「.create」メソッドを使用していますが、「検証に失敗しました: 添付ファイルを空白にすることはできません」というエラーが表示されます。

私が持っているものは(簡単に):

親モデル:

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):

= 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

コントローラーを適応させると、最初に親がデータベースに保存され、その後添付ファイルが保存されます(ここでattachableはRailsによって自動的に入力されます)が、この2段階の保存プロセスを避けて、両方の保存されるか、どちらも保存されません。

誰にもアイデアはありますか?

ありがとう!

4

0 に答える 0