【发布时间】:2016-06-06 21:05:23
【问题描述】:
我有一个表单,如果用户需要,我正在使用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
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 cocoon-gem