我为Lessons to Questions and Answers创建了一个嵌套的模型表单。它没有拿起咖啡脚本,所以我将咖啡代码添加为Javascript,但我收到错误,添加问题无法正常工作。任何人,请帮助。
Lesson.rb
has_many :questions
accepts_nested_attributes_for :questions, :allow_destroy => true
Question.rb
belongs_to :lesson
has_many :answers
accepts_nested_attributes_for :answers, :allow_destroy => true
Answer.rb
belongs_to :question
application_helper.rb
def link_to_add_fields(name, f, association) new_object = f.object.send(association).klass.new
id = new_object.object_id
fields = f.fields_for(association, new_object, :child_index => id) do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to(name, '#', :class => "add_fields", :data => {:id => id, :fields => fields.gsub("\n", "")}) end
管理员/经验/ _form.html.erb
<%= form_for([:admin,@lesson]) do |f| %>
<% if @lesson.errors.any? %>
<div class="notification error png_bg">
<a href="#" class="close"><img src="/assets/admin/icons/cross_grey_small.png" title="Close this notification" alt="close" /></a>
<div>
<h2><%= pluralize(@lesson.errors.count, "error") %></h2>
<ul>
<% @lesson.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
</div>
<% end %>
<label class="formlabel">Lesson Title</label>
<%= f.text_field :title %>
<%= f.fields_for :questions do |builder| %>
<%= render 'question_fields', :f => builder %>
<% end %>
<%= link_to_add_fields "Add Question", f, :questions %>
<%= f.submit 'Save', :class => 'button' %>
_question_fields.html.erb
<fieldset>
<%= f.label :content, "Question" %><br />
<%= f.text_area :content %><br />
<%= f.check_box :_destroy %>
<%= f.label :_destroy, "Remove Question" %>
<%= f.fields_for :answers do |builder| %>
<%= render 'answer_fields', :f => builder %>
<% end %>
<%= link_to_add_fields "Add Answer", f, :answers %>
</fieldset>
_answer_fields.html.erb
<fieldset>
<%= f.label :content, "Answer" %>
<%= f.text_field :content %>
<%= f.check_box :_destroy %>
<%= f.label :_destroy, "Remove Answer" %>
</fieldset>
这是我在head标记结束之前添加的javascript。我收到了&#34; $(&#39; form&#39;)的错误.on不是函数。 (&#39; $(&#39; form&#39;)。on&#39;,&#39; $(&#39; form&#39; ....
<script>
jQuery(function() {
$('form').on('click', '.remove_fields', function(event) {
$(this).prev('input[type=hidden]').val('1');
$(this).closest('fieldset').hide();
return event.preventDefault();
});
return $('form').on('click', '.add_fields', function(event) {
var regexp, time;
time = new Date().getTime();
regexp = new RegExp($(this).data('id'), 'g');
$(this).before($(this).data('fields').replace(regexp, time));
return event.preventDefault();
});
});
</script>
答案 0 :(得分:0)
Jquery .on()函数至少需要jquery 1.7才能工作。更新你的jquery或使用.bind()代替.on()。