1

我正在跟随这个Rails 教程,描述如何做嵌套模型表单。在 4:32,他开始描述如何用三个空模型预填充表单。有问题的两个模型是:

class Event < ActiveRecord::Base
    has_many :positions, dependent: :destroy
    accepts_nested_attributes_for :positions
end

和...

class Position < ActiveRecord::Base
    belongs_to :event
end

在我的事件控制器中,我将教程的代码添加到new方法中

def new
  @event = Event.new
  3.times { @event.positions.build }
end

我的事件的表单视图也被填充了。

<!-- /apps/views/events/_form.html.erb -->

<%= form_for(@event) do |f| %>
  <h3>Event Details</h3>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <!-- more fields here -->

  <h3>Create positions for the event</h3>
  <% f.fields_for :positions do |builder| %>
    <p>
      <%= builder.label :name %>
      <%= builder.text_field :name %>
    </p>
    <!-- more fields here -->
  <% end %>

  <!-- more fields here -->
<% end %>

但是,这些position字段没有出现在我的表单上。我已经rake db:migrated重新启动了服务器(Ctrl-Crake s)很多次,但没有任何效果。我究竟做错了什么?

4

1 回答 1

1

你错过了 attr_accessible 的东西。

在您的事件模型中添加:

attr_accessible :positions_attributes

看看这个例子:

class Contact < ActiveRecord::Base
  attr_accessible :addresses_attributes, :birth_date, :email, :gender, :name, :vat_number
  has_many :addresses
  accepts_nested_attributes_for :addresses
  #  validates_uniqueness_of :vat_number
  paginates_per 50

  def gender=(gender)
    gender = gender.downcase
    case gender.downcase
    when 'm'
      gender = 'male'
    when 'f'
      gender = 'female'
    else
    end
    write_attribute(:gender, gender)
  end
end


class Address < ActiveRecord::Base
  attr_accessible :city, :country, :postal_code, :street, :contact
  belongs_to :contact
end

此外,由于您正在学习该教程,因此您可能会在助手处停下来。这是 rails 3.2.13 的工作版本:

  def link_to_remove_fields(name, f)
    f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)", :class => "icon-remove")
  end

  def link_to_add_fields(name, f, association)
    new_object = f.object.class.reflect_on_association(association).klass.new
    fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
      render(association.to_s.singularize + "_fields", :f => builder)
    end
    link_to_function(name, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
  end

和 javascript 助手:

function remove_fields(link) {
    $(link).prev("input[type=hidden]").val("1");
    $(link).closest(".fields").hide();
}

function add_fields(link, association, content) {
    var new_id = new Date().getTime();
    var regexp = new RegExp("new_" + association, "g");
    $(link).parent().before(content.replace(regexp, new_id));
    $(link).parent().append('<input type="hidden" name="click" value="true" />');
    $("#last_id").val(new_id);
}
于 2013-07-15T22:13:27.540 回答