What I'm trying to do is to dynamically add form fragments inside a nested form in rails 3.1.1. I have this javascript inside CDATA generated from rails helper method which uses escape_javascript method. After calling link_to 'Add Ajax' as shown below, I 'm getting plain texts instead of HTML input fields being appended. What I really like to is have input fields are created, not plain garbage text. Please help.
<script type="text/javascript">
//<![CDATA[
var mappings='<p class=\"fields\">\n <input id=\"resource_synchronization_attributes_mappings_attributes_NEW_RECORD_source\" name=\"resource[synchronization_attributes][mappings_attributes][NEW_RECORD][source]\" size=\"30\" type=\"text\" />\n <input id=\"resource_synchronization_attributes_mappings_attributes_NEW_RECORD__destroy\" name=\"resource[synchronization_attributes][mappings_attributes][NEW_RECORD][_destroy]\" type=\"hidden\" value=\"false\" /><a href=\"#\" onclick=\"remove_fields(this); return false;\">remove<\/a>\n<\/p>\n\n\n\n'
//]]>
custom.js
replace_ids = function(s) {
var new_id = new Date().getTime()
return s.replace(/NEW_RECORD/g, new_id)
}
$(document).ready(function() {
$(".add_nested_item").click(function() {
var template = eval($(this).attr("href").replace(/.*#/, ''))
$($(this).attr("rel")).append(replace_ids(template))
return false
})
})
application_helper.rb
def generate_html(form_builder, method, options = {})
options[:object] ||= form_builder.object.class.reflect_on_association(method).klass.new
options[:partial] ||= method.to_s.singularize
options[:form_builder_local] ||= :f
form_builder.fields_for(method, options[:object], :child_index => "NEW_RECORD") do |f|
render(:partial => options[:partial], :locals => { options[:form_builder_local] => f })
end
end
def generate_template(form_builder, method, options = {})
escape_javascript generate_html(form_builder, method, options)
end
_form.html.erb
<div class="fields">
<p>
<%= f.label :start_datetime, "Start On" %><br />
<%= f.date_select :start_datetime %>&l开发者_运维技巧t;br />
</p>
<% content_for :java do %>
<%= "var mappings='#{generate_template(f, :mappings)}'" %>
<% end %>
<div id="mappings">
<%= f.fields_for :mappings do |builder| %>
<%= render 'mapping', :f => builder %>
<% end %>
</div>
<%= link_to 'Add Ajax', '#mappings', :class => 'add_nested_item', :rel => '#mappings' %>
</div>
models
class Resource < ActiveRecord::Base
has_many :utilities
has_many :people, :through => :utilities
has_many :person_attributes
has_one :synchronization
accepts_nested_attributes_for :synchronization
validates_presence_of :name
end
class Synchronization < ActiveRecord::Base
belongs_to :resource
has_many :mappings
accepts_nested_attributes_for :mappings, :reject_if => lambda { |a| a[:source].blank? }, :allow_destroy => true
#validates_presence_of :start_datetime
end
class Mapping < ActiveRecord::Base
belongs_to :synchronization
has_many :data, :class_name => 'PersonAttribute'
has_many :people, :through => :data
end
精彩评论