带有Rails 4强参数的嵌套属性

时间:2014-02-18 21:36:31

标签: ruby-on-rails

class Document < ActiveRecord::Base

  belongs_to :user

  has_many :attachments
  accepts_nested_attributes_for :attachments 

end

class DocumentsController < ApplicationController

  def new
    @document = get_user.documents.build
    3.times { @document.attachments.build }
  end

  def create
    @document = Document.new post_params
  end

  def post_params
    params.require(:document).permit(:id, :subject, :body, attachments_attributes:[:attachment])
  end

end

_form.html.slim

  = f.fields_for :attachments do |builder|
    = builder.file_field :attachment, multiple: true

问题在于:

post_params上的附件是空的:

{"id"=>"", "to"=>"5621", "subject"=>"Hello", "body"=>"World", "attachments_attributes"=>{"0"=>{}}}

3 个答案:

答案 0 :(得分:1)

看起来这是这样做的方法:

  def post_params
    params.require(:document).permit(:id, :subject, :body, attachments_attributes:[:attachment => []])
  end

答案 1 :(得分:0)

您的表单标签上可能缺少multipart: true

答案 2 :(得分:0)

可能

def post_params
  params.require(:document).permit(:id, :subject, :body,
                                   attachments_attributes: ['0'])
end