Rails:3times {model1.model2.build}没有产生任何东西

时间:2013-07-15 22:04:23

标签: ruby-on-rails rake ruby-on-rails-4

我正在跟随此Rails tutorial描述如何进行嵌套模型表单。在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),但没有任何效果。我做错了什么?

1 个答案:

答案 0 :(得分: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);
}