Nested Model Forms - Railscast #196 revised - Adding fields via jQuery not working

不打扰是莪最后的温柔 提交于 2020-01-01 14:36:01

问题


I was following the Railscast #196 revised and everything went basically fine, but I am not able to add new fields to the nested form. The "remove fields" function works nicely, but after click on "link_to_add_fields", the browser jumps to the top of the page, and no new field appears.

There are already a ton of questions to this railscast, like here or here, and I tried to read all of them, but most of them are referring to the original casts from 2010. I am stuck for hours now, and I can't figure out, where my problem is. Sorry, if its a rookie mistake, I am quite new to rails. Any help would be really appreciated!

I was following the #196 revised version, using Rails 3.2.13, Ruby 1.9.3

models/post.rb

class Post < ActiveRecord::Base
    attr_accessible :content, :title, :image, :postfiles_attributes
    has_many :postfiles, :dependent => :destroy 
    accepts_nested_attributes_for :postfiles, allow_destroy: true
end

models/postfile.rb

class Postfile < ActiveRecord::Base
  attr_accessible :dropbox, :gdrive, :post_id
  belongs_to :post
end

views/posts/_form.html.erb

<%= simple_form_for @post do |f| %>

  <%= f.fields_for :postfiles do |builder| %>
       <%= render 'postfile_fields', f: builder %>
  <% end %>
  <%= link_to_add_fields "Add File", f, :postfiles %>

<% end %>

views/posts/_postfile_fields.html.erb

<fieldset>  
    <%= f.text_field :dropbox %>
    <%= f.hidden_field :_destroy %>
    <%= link_to "remove", '#', class: "remove_fields" %>
</fieldset>

postfiles.js.coffee

jQuery ->
   $('form').on 'click', '.remove_fields', (event) ->
    $(this).prev('input[type=hidden]').val('1')
    $(this).closest('fieldset').hide()
    event.preventDefault()

  $('form').on 'click', '.add_fields', (event) ->
    time = new Date().getTime()
    regexp = new RegExp($(this).data('id'), 'g')
    $(this).before($(this).data('fields').replace(regexp, time))
    event.preventDefault()

application_helper.rb

module ApplicationHelper
  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
end

Upfront, thank you so much for your help!

UPDATE: I am using simple-form. See the _form file above. Could this be an issue?

UPDATE II:

I get an Javascript error, not sure if this could be an issue for the problem here: Chrome calls it "Uncaught SyntaxError: Unexpected reserved word " and Firebug calls it "SyntaxError: unterminated string literal". The error points to this js code part:

loadData: function(data){

   this.$editor.addClass('st-block__editor');

   this.$editor.html("
   <div class='st-block__inner'>
      <div class='media'>
        <a class='pull-left' >
          <img class='media-object link-pic' src='" + data.thumbnail_url + "'>
        </a>
        <div class='media-body'>
          <div class='link-source'>" + data.provider_name + "</div>
          <div class='link-title'> <a href='#'>" + data.title + "</a></div>    
          <div class='link-description'>" + data.description + "</div>  
        </div>
      </div>
    </div>
  ");
},

UPDATE 3:

Could the posts controller be part of the issue?

This is my posts_controller.rb

def new
    @post = current_user.posts.new
    @post.postfiles.build

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @post }
    end
  end

Thanks again for all your help!


回答1:


I found via accident Railscast #403 on Dynamic Forms in which nested forms were briefly part of the tutorial, too. Ryan used in this episode an edited code for the javascript part to make the code compatible with Turbolinks. I tried the version below in my postfiles.js.coffee and it worked! The add fields link is finally generating new fields.

$(document).on 'click', 'form .remove_fields', (event) ->
  $(this).prev('input[type=hidden]').val('1')
  $(this).closest('fieldset').hide()
  event.preventDefault()

$(document).on 'click', 'form .add_fields', (event) ->
  time = new Date().getTime()
  regexp = new RegExp($(this).data('id'), 'g')
  $(this).before($(this).data('fields').replace(regexp, time))
  event.preventDefault()



回答2:


You should watch out for singular and plural forms. The file name of your model should be postfile.rb instead of postfiles.rb

Same goes for the _postfiles_fields.html.erb which should be _postfile_fields.html.erb

So, basically the function can't find the template, because it's in plural and not singular form, but it gets called by its singular form. Change this and you should be fine. Rest of the code looks good.



来源:https://stackoverflow.com/questions/20136241/nested-model-forms-railscast-196-revised-adding-fields-via-jquery-not-worki

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!