这是一个多态嵌套关联,可以在客户端使用 javascript 进行处理。所以,最后对于嵌套字段,我使用了插件Numerous.js。只需按照链接的 qucikstart 部分中给出的步骤,从 Github 下载 many.js 文件并保存到 assets/javascripts。
在我的代码中,
profile.rb
class Profile < ApplicationRecord
has_many :degrees, :as => :degreeable
accepts_nested_attributes_for :degrees, :reject_if => :all_blank, allow_destroy: true
belongs_to :user, :class_name => 'User', :foreign_key => 'user_id'
end
学位.rb
class Degree < ApplicationRecord
belongs_to :degreeable, polymorphic: true
end
profiles/_form.html.erb
<div id="fields-for-list" class="numerous">
<%= f.fields_for :degrees, Degree.new, :child_index => 'replace_this' do |degree_form| %>
<%= degree_form.select :level, options_for_select(Job::EDUCATION, params[:level]), include_blank: "Select Degree", :class => 'span5' %>
<%= degree_form.text_field :description, placeholder: "Add a new Degree here..."%>
<%= link_to 'x Remove', '#', :class => 'numerous-remove', type: 'button' %>
<% end %>
</div>
<div id="list"></div>
<%= link_to (fa_icon 'plus').to_s + 'Add a Qualification', '#', :id => 'add-to-list' %>
最后,使用强大的参数,
def profile_params
params.require(:profile).permit(:user_id, :first_name, :last_name, degrees_attributes:[:id, :level, :description])
end
请注意,我已经为多态关联设置了带有 2 个额外字段的学位表:-"degreeable_id" & "degreeable_type" 并且在进入 DB 时,这两个字段自动填充了新创建的 profile_id 和“Profile”(多态性与度数相关联的模型)。
众多.js 中的技巧是创建具有唯一临时 ID 的每个嵌套表单记录(此处为学位),例如 Time.now.to_i,因此现在在客户端创建/销毁的每个学位记录都将具有 diff degree_attribute 'id'。希望对其他人有所帮助。