我有一个表单,如果用户需要,我使用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
答案 0 :(得分:2)
该表单显示了一个简介,包含了所有现有的教育。因此,如果您希望默认显示教育字段,请在呈现表单之前添加教育。
因此,在您的控制器中,您可以执行类似
的操作@profile = Profile.new
你可以建立初级教育,以便以下列形式出现:
@profile = Profile.new
@profile.educations.build