使用 cocoon 动态添加前显示字段 gem

Display fields before dynamically adding with cocoon gem

我有一个表单,如果用户需要,我正在使用 cocoon gem 添加额外的字段。就目前而言,它显示 add educations link 然后出现字段,我希望在表单中显示字段,然后如果需要,用户单击 add education link 来呈现字段。除此之外一切正常,模型都设置正确,但无法解决这个问题。

new.html.erb

<%= form_for @profile do |f| %>
  <%= f.label :bio %>
  <%= f.text_area :bio %>

  <%= f.label :university %>
  <%= f.text_field :university %> <br>

  <%= f.label :course %>
  <%= f.text_field :course %> <br>

  <%= f.label :finishedDate %>
  <%= f.text_field :finishedDate %> <br>

  <div id="educations">
    <%= f.fields_for :educations do |education| %>
      <% render 'education_fields', f: education %>
    <% end %>
    <div class="links">
      <%= link_to_add_association 'add education', f, :educations %>
    </div>
  </div>

  <%= f.button :submit %>
<% end %>

_education_fields.html.erb

<div class="nested-fields">
  <%= f.label :university %>
  <%= f.text_field :university %> <br>

  <%= f.label :course %>
  <%= f.text_field :course %> <br>

  <%= f.label :finishedDate %>
  <%= f.text_field :finishedDate %> <br>

  <%= link_to_remove_association "remove education", f %>
</div>

profiles_controller.rb

class ProfilesController < ApplicationController

  def index
    @profiles = Profile.all
  end

  def new
    @profile = Profile.new
    @profile = educations.build
  end

  def create
    @profile = Profile.create(profile_params)
    redirect_to profiles_path
  end

  def show
    @profile = Profile.find(params[:id])

  end

  def edit
    @profile = Profile.find(params[:id])
  end

  def update
    @profile = Profile.find(params[:id])
    @profile.update(profile_params)
    redirect_to(profiles_path(@profile))
  end

  private

  def profile_params
    params.require(:profile).permit(:bio, educations_attributes:[:id, :university, :course, :finishedDate, :destroy])
  end

end

该表格显示了个人资料及其所有现有教育。因此,如果您想默认显示教育领域,请在呈现表单之前添加教育。

所以,在你的控制器中,你可以做类似

的事情
@profile = Profile.new

您可以建立初始教育,它会以以下形式显示:

@profile = Profile.new
@profile.educations.build