rails: 嵌套资源保存空记录

rails: nested resources saving empty records

我创建了一种简单形式的嵌套资源。我无法正确保存 child 表单 todo_item。当我单击 "create todo item" 按钮时,无论我在标题字段中输入什么内容,都会创建并保存一条空记录。

代码非常简单,parent 记录保存良好。 child 记录正在显示,所以我不知道哪里出了问题。请帮忙。

我的模特:

class TodoItem < ActiveRecord::Base
  belongs_to :todo_list
end

class TodoList < ActiveRecord::Base
  has_many :todo_items, dependent: :destroy
end

我的控制器:

class TodoItemsController < ApplicationController
  before_action :set_todo_list
  before_action :set_todo_item, only: [:show, :edit, :update, :destroy]

  def new
    @todo_item = @todo_list.todo_items.new
  end

  def create
    @todo_item = @todo_list.todo_items.new

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

  private

    def set_todo_item
      @todo_item = @todo_list.todo_items.find(params[:id])
    end

    def set_todo_list
      @todo_list = TodoList.find(params[:todo_list_id])
    end

    def todo_item_params
      params.require(:todo_item).permit(:title, :due_date, :description, :text, :completed)
    end

end

View.html.erb:

<h1>New Todo Item</h1>

<%= render 'form' %>

<%= link_to 'Back', @todo_list %>

_form.html.erb:

<%= form_for([@todo_list, @todo_item]) do |f| %>
 ...

  <div class="field">
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

您在此处初始化 @todo_item

def create
  @todo_item = @todo_list.todo_items.new # <===== INITIALIZED HERE

  respond_to do |format|
    if @todo_list.save # <===== SAVED HERE WITHOUT EVER ASSIGNING VALUES.
      format.html { redirect_to @todo_list, notice: 'Todo item was successfully created.' }
      format.json { render :show, status: :created, location: @todo_list }
    else
      format.html { render :new }
      format.json { render json: @todo_list.errors, status: :unprocessable_entity }
    end
  end
end

但是,不要向 new 提供任何参数。因此,新记录没有任何价值。

相反,做一些更像:

@todo_item = @todo_list.todo_items.new(todo_item_params)

也许你还应该添加一些验证,这样你就可以避免这种情况。

您需要修改创建方法:

def create
@todo_item = @todo_list.todo_items.create(todo_item_params)

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

结束