fields_for在编辑期间重复

时间:2014-08-08 11:34:59

标签: ruby-on-rails ruby-on-rails-3

我跟着this railscast。

控制器: project_sub_types_controller.rb

def new
    @svn_repos = ['svn_software','svn_hardware']
    @project_sub_type = ProjectSubType.new
    @project_sub_type.repositories.build
end

def edit
  @svn_repos = ['svn_software','svn_hardware']
  @project_sub_type = ProjectSubType.find(params[:id])
end

型号: project_sub_type.rb

class ProjectSubType < ActiveRecord::Base
  belongs_to :project_type
  has_many :repositories, :dependent => :destroy

  def repositories_attributes=(repos_attributes)
    repos_attributes.each do |attributes|
      repositories.build(attributes)
    end
  end
end

查看: _form.html.erb

<%= form_for @project_sub_type, :html => {:class => 'project_subtype_form'} do |f| %>
  <%= f.label :name, "Project sub type name" %>
  <%= f.text_field :name %>
  <% for repos in @project_sub_type.repositories %>
      <%= fields_for "project_sub_type[repositories_attributes][]", repos do |repos_form| %>
          <% @svn_repos.each do |repos| %>
              <%= repos_form.check_box :repos_name, {}, "#{repos}", nil %>
              <%= h repos -%>
          <% end %>
      <% end %>
  <% end %>
<%= f.submit "Save"%>

这在创建新记录时非常有效。但是Y在编辑期间执行fields_for重复。在创建过程中,我看到2个复选框,但在编辑过程中有4个复选框,与其他2个复选框重复。我究竟做错了什么?

更新:点击编辑次数越多,复制次数就越多。

1 个答案:

答案 0 :(得分:0)

<% for repos in @project_sub_type.repositories %>
      <%= fields_for "project_sub_type[repositories_attributes][]", repos do |repos_form| %>
          <% @svn_repos.each do |repos| %>
              <%= repos_form.check_box :repos_name, {}, "#{repos}", nil %>
              <%= h repos -%>
          <% end %>
      <% end %>
  <% end %>

摆脱它并做:

  <%= f.fields_for :repositories do |repo_form| %>
    <% @svn_repos.each do |rep| %>
      <%= repo_form.check_box :repos_name, {}, rep, nil %>
      <%= h rep -%>
    <% end %>
  <% end %>

还要删除模型中的repositories_attributes=方法并添加accepts_nested_attributes_for :repositories

您链接的railscast已有7年历史。 :)