首页 文章

动态嵌套表单总是创建一个额外的空白条目 - 使用formtastic_coocoon

提问于
浏览
4

我正在使用formtastic和formtastic_cocoon来创建嵌套表单 .

所有这些似乎都能很好地动态地将嵌套表单添加到现有表单中,但有一个例外 .

我有用户和用户都有条目 .

当我创建一个用户并添加一个条目时,我最终得到了

-User
   - Entry (empty)
   - Entry Test 1

我应该只有

-User
   - Entry Test 1

我不确定为什么空白条目总是出现 .

我的模特是

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

我的创建控制器是(我认为这是正确的控制器)

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

空条目显示在数据库中,所以我认为这不是html.erb文件的问题,但我可以在这里发布,如果这会有所帮助 .

1 回答

  • 1

    事实证明这可能是formtastic_cocoon处理表单的方式的问题 .

    查看html源代码时,嵌套表单位于页面中,但隐藏 .

    我将模型改为

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

相关问题