Robin Winton
Robin Winton

Reputation: 601

nested form is not displayed

I have the following form declaration for a new kindergarten

<%= form_for @kindergarten, :html => {:multipart => true}  do |f|%>

                <%= render 'shared/error_messages', object: f.object %>
            </br>   
                <%= f.fields_for :photos do |p| %>
                    <%= p.label 'upload photo'%>
                    <%= p.file_field :image %>
                <% end %>
            </br>
                <%= render 'about_company', f: f%>
            </br>
                <%= render 'contact', f: f %>
                <%= f.submit "Create my account", class: "btn btn-large btn-primary" %>
            <%end%>

The logic behind this is that 1 kindergarten can have multiple photos.

Here are the model declarations:

Kindergarten

has_many :photos, limit: 7, dependent: :destroy   
accepts_nested_attributes_for :photos

Photo

  attr_accessible :image, :logo, :kindergarten_id
  belongs_to :kindergarten
  mount_uploader :image, ImageUploader

  validates :kindergarten_id, presence: true
  validates :photo, presence: true

I am struggling with this for a few hours now, and I can't understand why the "upload file" button and label are not showing up. When i say now showing up, i mean they are completely ignored and not present in the rendered html.

Upvotes: 0

Views: 54

Answers (1)

rossta
rossta

Reputation: 11494

Before rendering the form for a new @ kindergarden, you'll need to build a photo association for this to work:

def new
  @kindergarden = Kindergarden.new
  @kindergarden.photos.build # provides a photo object to use in the form
  # rest of your action
end

Also, if you wanted multiple photo fields in the form, you could do something like:

 5.times { @kindergarden.photos.build } 

Upvotes: 1

Related Questions