Fields_for missing when trying to add accepts_nested_attributes_for

Im working on a simple form function that adds an image through a nested form.

A photo model in which all my uploaded images should be stored.

class Photo < ActiveRecord::Base

  belongs_to :posting

  has_attached_file :image, styles: { large: "500x500>", medium: "300x300>", thumb: "100x100#" }, default_url: "/images/:style/missing.png"
  validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/

end

fragment of my nested form (in form)

<%= post.fields_for :photos, html: { multipart: true } do |photo| %>
            <%= photo.label :image %>
            <%= photo.file_field :image %>
        <% end %>

Everything is fine, but when I uncomment the line accepts_nested_attributes_for. My nested form disappears!

class Posting < ActiveRecord::Base

    belongs_to :subcategory
    belongs_to :category

    has_many :photos

    #accepts_nested_attributes_for :photos
end
+4
source share
2 answers

I assume you assigned an @post instance variable in the new PostsController action. You must add the build_photo method to the new action:

def new
  @post = Post.new
  @post.build_photo
end

This should also show your nested form.

+2
source

. " " API fields_for

, .

<% post.photos.each do |photo| %>
 <%= post.fields_for :photos, photo, html: { multipart: true } do |photo_fields| %>
   <%= photo_fields.label :image %>
   <%= photo_fields.file_field :image %>
  <% end %>
<% end %>
+2

All Articles