2

I'm following this tutorial and the author is using Slim. Since I more familiar with standard Rails form, I try to change the slim markup to normal form like so:

new.html.erb

<%= render 'form' %>

_form.html.erb

<%= form_for(@user) do |f| %>
  <%= f.text_field :name %>

  <br><br>

  <%= fields_for :user_photos do |photo| %>
    <%= render "user_photo_fields", f: photo %>
    <span class="links">
      <%= link_to_add_association "add photo", f, :user_photos %>
    </span>
  <% end %>

  <%= f.submit %>
<% end %>

_user_photo_fields.html.erb

<div class="nested-fields">
    <div class="field">
        <%= f.file_field :photo %>
    </div>
    <%= link_to_remove_association "remove", f %>
</div>

And, this is my models:

class User < ActiveRecord::Base
    has_many :user_photos
    validates_presence_of :name
    accepts_nested_attributes_for :user_photos, allow_destroy: true
end

class UserPhoto < ActiveRecord::Base
    belongs_to :user
    mount_uploader :photo, PhotoUploader
end

And lastly, strong params inside the users_controller.rb. I didn't touch the rest methods inside the controller because I'm using rails g scaffold user name:string generator.

def user_params
      params.require(:user).permit(:name, user_photos_attributes: [:id, :photo, :_destroy])
    end

enter image description here

I get this error:

undefined method `new_record?' for nil:NilClass

What am I missing here?

Zulhilmi Zainudin
  • 9,017
  • 12
  • 62
  • 98

2 Answers2

3

I believe it's just a simple typo - your fields_for :user_photos should be f.fields_for :user_photos (so that it's properly connected to the parent form).

sevenseacat
  • 24,699
  • 6
  • 63
  • 88
  • After add `f` in front of `fields_for`, I only get the user name field and the nested fields is gone. http://i.imgur.com/DapYxag.png – Zulhilmi Zainudin Mar 01 '16 at 04:41
  • Which is normal, because at the moment of creation there are no nested items, unless you create one in the controller, something like `@user.user_photos.build` – nathanvda Mar 01 '16 at 08:28
0

please try with this.

class User < ActiveRecord::Base
  has_many :user_photos
  validates_presence_of :name
  accepts_nested_attributes_for :user_photos, allow_destroy: true
end

can you try to fix this by removing the f

  <div class="nested-fields">
        <div class="field">
            <%= file_field :photo %>
        </div>
        <%= link_to_remove_association "remove" %>
  </div>