获取嵌套表单到工作轨道?

时间:2014-05-28 12:12:12

标签: ruby-on-rails

我有这些模特:

class List < ActiveRecord::Base

    has_many :list_items, :dependent => :destroy
    accepts_nested_attributes_for :list_items, :reject_if => lambda { |a| a(:task.blank?)}
end

class ListItem < ActiveRecord::Base

    belongs_to :list
end

和这个控制器:

class ListsController < ApplicationController

  def index
    @lists = List.order("lists.created_at DESC")
  end

  def show
    @list = List.find(params[:id])
  end

  def new
    @list = List.new({:name => Time.now.strftime("%A %d %B")})
    3.times { @list.list_items.build}
  end

  def create
    @list = List.new(list_params)

    if @list.save
      flash[:notice] = "List successfully added."
      redirect_to(:action => 'index')
    else
      render(:action => 'new')
    end
  end

  def edit
    @list = List.find(params[:id])
  end

  def update
    @list = List.find(params[:id])

    if @list.update_attributes
      flash[:notice] = "List updated successfully."
      redirect_to(:action => 'index')
    else
      render(:action => 'edit')
    end
  end


  def delete
    @list = List.find(params[:id])
  end

  def destroy 
    @list = List.find(params[:id]).destroy
    flash[:notice] = "List successfully deleted"
    redirect_to(:action => 'index')
  end

  private
  def list_params
    params.require(:list).permit(:name, :task)
  end

end

以及此表格:

<%= form_for @list do |f| %>

<p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
</p>
    <%= f.fields_for :list_items do |builder| %>
        <p>
            <%= builder.label :task %><br />
            <%= builder.text_field :task %>
        </p>

    <% end %>
    <p><%= f.submit "Create" %></p>
<% end %>

你可能会看到我想要做的事情 - &gt;创建一个表单,在其中创建一个新列表,然后将任务添加到该列表但由于某种原因,每当我点击表单上的提交名称保持但任务不保存?

1 个答案:

答案 0 :(得分:1)

我解决了问题,我需要将list_item属性添加到列表控制器。我试图用attr_accessible在我的模型中使用rails 3方式,这一直给我一个错误。我需要更新控制器以将其放在底部:

def list_params
    params.require(:list).permit(:name, :list_items_attributes => :task)
  end