A dynamic nested form always creates an additional blank entry - using formtastic_coocoon

I use formtastic and formtastic_cocoon to create a nested form.

Everything seems to work well, dynamically adding a nested form to an existing form, with one exception.

Users and users have entries.

When I create a user and add a record, I get

  -User
    - Entry (empty)
    - Entry Test 1

I must have

  -User
    - Entry Test 1

I'm not sure why a blank entry always appears.

My models

  class User <ActiveRecord :: Base
    validates: name,: presence => true
    has_attached_file: photo

    has_many: tasks,: dependent =>: destroy

    accepts_nested_attributes_for: tasks,: allow_destroy => true

 end

 class Task <ActiveRecord :: Base
    attr_accessible: entry

    belongs_to: user


 end

my creation controller (I think this is the right controller)

  def create
     @user = User.new (params [: user])
     if @ user.save
       flash [: notice] = "Successfully created user."
       redirect_to @user
     else
       render: action => 'new'
     end
   end

  def create
     @task = Task.new (params [: task])
     if @ task.save
       flash [: notice] = "Successfully created task."
       redirect_to @task
     else
       render: action => 'new'
     end
   end

Empty entries are displayed in the database, so I don't think this is a problem with the html.erb files, but I can post them here if that helps.

+4
source share
1 answer

Turns out this might be a problem with the way formtastic_cocoon handles forms.

When viewing the html source, the nested form is on the page, but hidden.

I changed the model to

  accepts_nested_attributes_for: tasks,: reject_if => proc {| attributes |  attributes [: entry] .blank?},: allow_destroy => true
+1
source

Source: https://habr.com/ru/post/1338973/


All Articles