Dex
Dex

Reputation: 12749

Nested Attributes with Rails 4 Strong Parameters

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

Here is the problem:

The attachments on my post_params are empty:

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

Upvotes: 1

Views: 253

Answers (3)

Dex
Dex

Reputation: 12749

Looks like this is the way to do it:

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

Upvotes: 1

vrybas
vrybas

Reputation: 1719

possibly

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

Upvotes: 0

Simon
Simon

Reputation: 1736

It looks like you might be missing multipart: true on your form tag.

Upvotes: 0

Related Questions