Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 498
YvonC Avatar asked May 13 '26 00:05

YvonC


1 Answers

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()
like image 56
YvonC Avatar answered May 14 '26 15:05

YvonC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!