开发者

Javascript code just produces HTML printout, fails to render it

开发者 https://www.devze.com 2023-04-04 20:19 出处:网络
I\'m a newbie to RoR and am following this railscast that explains how to remove and add elements within nested forms. In my case, I\'m trying to allow users to add/remove \"items\" from a shopping \"

I'm a newbie to RoR and am following this railscast that explains how to remove and add elements within nested forms. In my case, I'm trying to allow users to add/remove "items" from a shopping "list." Unfortunately, however, when I click "add item" in my browser, HTML is printed out, instead of rendered. Here's what it outputs:

<div class ="fields"> Quantity: <input id="list_items_attributes_1315942810959_quantity" name="list[items_attributes][1315942810959][quantity]" size="7" type="text" /> Name: <input id="list_items_attributes_1315942810959_name" name="开发者_运维百科list[items_attributes][1315942810959][name]" size="30" type="text" /> Category: <select id="list_items_attributes_1315942810959_category" name="list[items_attributes][1315942810959][category]"><option value="Produce">Produce</option> <option value="Dairy">Dairy</option></select> <p><input id="list_items_attributes_1315942810959__destroy" name="list[items_attributes][1315942810959][_destroy]" type="hidden" value="false" /><a href="#" onclick="remove_fields(this); return false;">remove</a></p> </div>
Add Item

I feel like I'm missing something simple. Is there some switch that I can turn on to get this to render? Thanks!


In case it's helpful, here's my list model:

class List < ActiveRecord::Base
  has_many :items, :dependent => :destroy
  accepts_nested_attributes_for :items, :reject_if => lambda { |a| a[:name].blank?}, :allow_destroy => true

  belongs_to :user

end

Here's my short form for adding items to a list:

<%= form_for @list do |f| %>
<p>
    <%= f.label :date %>
    <%= f.date_select :date %>
</p>
    <%= f.fields_for :items do |builder|%>
        <%= render "item_fields", :f => builder %>
    <% end %>
<p><%= link_to_add_fields "Add Item", f, :items %></p>  
<%= submit_tag "Create List" %>
<% end %>

Here's my link_to_add_fields method in my application helper (it's a verbatim copy from the railscast):

  def link_to_add_fields(name, f, association)
    new_object = f.object.class.reflect_on_association(association).klass.new
    fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
      render(association.to_s.singularize + "_fields", :f => builder)
    end
    link_to_function(name, h("add_fields(this, '#{association}', '#{escape_javascript(fields)}')"))
  end

And finally, here's my add_fields function in my application.js file:

function add_fields(link, association, content) {
  var new_id = new Date().getTime();
  var regexp = new RegExp("new_" + association, "g")
  $(link).up().insert({
    before: content.replace(regexp, new_id)
  });
}
0

精彩评论

暂无评论...
验证码 换一张
取 消