1

嘿,我正在关注 Ryan Bates ( http://railscasts.com/episodes/197-nested-model-form-part-2 )的 Railscast #196,197嵌套表单,但它没有用。

我的模型:

    class Book < ActiveRecord::Base
      attr_accessible :abstract, :status, :titel, :user_tokens, :chapters_attributes,  :user_ids

      has_and_belongs_to_many :users
      attr_reader :user_tokens

      has_many :chapters, :dependent => :destroy, :autosave => true, :order => 'slot'

      validates :titel, :presence => true

      accepts_nested_attributes_for :chapters, :allow_destroy => true

      after_initialize :init
      def init
        self.status = false if self.status?
      end

      def user_tokens=(ids)
        self.user_ids = ids.split(",")
      end
    end

部分 _chapter_fields.erb :

        <div class="fields">
            <%= f.label :chapter_title, "Chapter Title" %>
            <%= f.text_field :chapter_title %>
            <%= f.hidden_field :_destroy %>
            <%= link_to_remove_fields "remove", f %>
        </div>

表格 :

        <p><%= f.label :chapters, "Chapters:" %></p>

        <%= f.fields_for :chapters do |builder| %>
            <%= render "chapter_fields", :f => builder %>
        <% end %>
        <p><%= link_to_add_fields "Add chapter", f, :chapters , [] %></p>

application_helper.rb :

       module ApplicationHelper

         def link_to_remove_fields(name, f)
           f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
         end

         def link_to_add_fields(name, f, association, attributes)
           if(attributes.size == 0)
             new_object = f.object.class.reflect_on_association(association).klass.new
           else
             new_object = f.object.class.reflect_on_association(association).klass.new(attributes)
           end
           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, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
         end
       end  

应用程序.js:

      //= require jquery
      //= require jquery_ujs
      //= require_tree .


      function remove_fields(link) {
            $(link).previous("input[type=hidden]").value = "1";
            $(link).up(".fields").hide();
      }

      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)
        });
      }

一切都和教程一模一样……我错过了什么???

我发现了同样的问题,但没有答案...... 同样的问题

那是我的萤火虫输出:

   <a rel="nofollow" data-method="delete" data-confirm="Are you sure?" href="/books/6">Destroy</a>
4

0 回答 0