使用cocoon gem,但在第一个输入字段后无法保存数据

时间:2015-07-15 03:27:59

标签: ruby-on-rails ruby-on-rails-4 nested-attributes cocoon-gem

我尝试在我的应用程序中实现cocoon,但在第一个输入字段后保存数据时遇到问题。

我尝试过这个例子,但没有运气。

我可以将第一个字段保存到数据库中,但是当我添加更多字段时,其他字段都没有发生。

_form.html.erb

<%= simple_form_for(@project) do |f| %>
  <%= f.input :project_name %>
  <%= f.hidden_field :user_id %>
  <div id="tasks">
    <%= f.simple_fields_for :tasks do |g| %>
      <%= render 'task_fields', :f => g %>
    <% end%>

    <%= link_to_add_association 'add task', f, :tasks %>
  </div>
  <%= f.button :submit %>
<% end %>

_task_fields.html.erb

<li class="control-group nested-fields">
  <div class="controls">
    <%= f.label :task %>
    <%= f.text_field :task %>
  </div>

  <%= link_to_remove_association "remove task", f %>
</li>

控制器

params.require(:project).permit(
  :user_id, :project_name, 
  tasks_attributes: [:id, :task, :_destroy])

我补充道:

//= require cocoon
application.js

中的

项目模型

class Project < ActiveRecord::Base
  belongs_to :user
  has_many :tasks

  accepts_nested_attributes_for :tasks, :reject_if => :all_blank, allow_destroy: true

end

任务模型

class Task < ActiveRecord::Base
  belongs_to :project
end

我想我说得对吗?我可以单击“添加任务”链接并弹出一个新字段,但这些新字段不会保存。

来自控制台的POST

编辑

Processing by ProjectsController#create as HTML
  Parameters: {
       "utf8"=>"✓", 
       "authenticity_token"=>"blah", 
       "project"=>{"project_name"=>"cocoon test", 
       "tasks_attributes"=>{
               "0"=>{"task"=>"fix this!", 
                     "_destroy"=>"false"
                    }}}, 
       "commit"=>"Create Project"}
  (0.2ms)  begin transaction
  SQL (1.5ms)  INSERT INTO "projects" ("project_name", "created_at", "updated_at") VALUES (?, ?, ?)  [["project_name", "cocoon test"], ["created_at", "2015-07-15 03:26:09.444377"], ["updated_at", "2015-07-15 03:26:09.444377"]]
  SQL (0.4ms)  INSERT INTO "tasks" ("task", "project_id", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["task", "fix this!"], ["project_id", 8], ["created_at", "2015-07-15 03:26:09.450324"], ["updated_at", "2015-07-15 03:26:09.450324"]]
   (8.4ms)  commit transaction
Redirected to http://localhost:3000/projects/8
Completed 302 Found in 24ms (ActiveRecord: 10.4ms)

编辑2 发布项目控制器方法createnew

def create
  @project = Project.new(project_params)

  respond_to do |format|
    if @project.save
      format.html { redirect_to @project, notice: 'Project was successfully created.' }
      format.json { render :show, status: :created, location: @project }
    else
      format.html { render :new }
      format.json { render json: @project.errors, status: :unprocessable_entity }
    end
  end
end

def new
  @project = Project.new
  @project.tasks.build
end

0 个答案:

没有答案