0

I'm new to rails. I appreciate any help. I followed railscast episode 196. I created a nested form that is working fine and saving to the database. I want to add field dynamically but the new added fields are not saving to the database.

Here is the helper method I created: 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 |d|
      render(association.to_s.singularize + "_fields", :f => d)
    end
    link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("/n", "")})
  end
end

_form.html.erb

 <%= form_for(@track, html: { multipart: true}) do |f| %>
      <%= f.label :name %>
      <%= f.text_field :name, class: "form-control"%>

      <%= f.label :category %>
      <%= f.text_field :category, class: "form-control" %>

      <div class="form-group picture">
        <%= f.label :picture %>
        <%= f.file_field :picture, class: 'form-control', accept: 'image/jpeg,image/gif,image/png' %>
      </div>

      <%= f.label :description %>
      <%= f.text_field :description, class: "form-control" %>

      <%= f.label :tags %>
      <%= f.text_area :tags, class: "form-control" %>

<div class="row">
  <div class="well col-md-8 col-md-offset-2">
      <%= f.fields_for :docs do |d| %>
          <%= render 'doc_fields', f: d %>
      <% end %>
      <%= link_to_add_fields("Add Lesson", f, :docs) %>
  </div>
</div>
<%= f.submit(@track.new_record? ? 'Publish Track' : 'Update Track', class: "btn btn-success pull-right") if user_signed_in? %>

  <% end %>

tracks.js.coffee

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

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

track.rb

class Track < ActiveRecord::Base
  # model associations
  belongs_to :user
  has_many :docs

  # nested model
  accepts_nested_attributes_for :docs, allow_destroy: true
end

track_controller.rb

 def new
    @track = Track.new
    @track.docs.build
  end

  def create
    @track = Track.new(track_params)
    @track.user = current_user
    if @track.save
      flash[:success] = "Your track was created succesfully!"
      redirect_to track_path(@track)
    else
      render :new
    end
  end

 def track_params
      params.require(:track).permit(:name, :category, :description, :tag, :picture,
                                :docs_attributes => [:id, :title, :format, :_destroy])
    end

The remove is working fine. The add isnt saving to the database. I appreciate your help!

moelgendy
  • 1
  • 1
  • Could you please tell us what error you are Getting in log file ?? – Gupta Dec 10 '15 at 04:50
  • Do you have accepts_nested_attributes_for in your model? And do you allow them in your params? – Doon Dec 10 '15 at 04:56
  • @Doon Yes, I have accepts_nested_attributes. All the attributes are successfully save except the one i add using the add_fields link. I updated my post with the model.rb – moelgendy Dec 10 '15 at 05:05
  • @Vinay There is no error. I hit add lesson, it adds a field. I add data to the field and hit save. Everything is saved except the added fields. – moelgendy Dec 10 '15 at 05:05
  • Are you white listing all the params correctly ? maybe posting the controller code for white listing and the 'doc_fields' partial will give more idea. – Sajan Dec 10 '15 at 07:32
  • First look for params sended by form. And try to use this gem https://github.com/nathanvda/cocoon – Sergey Gorlanov Dec 10 '15 at 15:07
  • @SergeyGorlanov I'm using cocoon gem. Do I need to change my forms syntax to similar to whats in cocoon's read me page? – moelgendy Dec 10 '15 at 15:24
  • @moelgendy Post your exact params permitted. Nested params have to be permitted as an array. http://stackoverflow.com/questions/18436741/rails-4-strong-parameters-nested-objects – Bryan Dimas Dec 10 '15 at 15:46
  • @BryanDimas updated the post with the tracks_controller.rb – moelgendy Dec 10 '15 at 16:17
  • @moelgendy Good. Shouldn't you be permitting `:docs => [:attr_one, :attr_two]` instead of `:docs_attributes => [:attr_one, :attr_two]`? Now can you show us the params being posted by the form? From the terminal. – Bryan Dimas Dec 10 '15 at 16:47

1 Answers1

0

You need to add multipart to your form_for:

f.fields_for :docs, :html => { :multipart => true }, do |d|

And something is wrong with your _form, you have the link_to_add outside the form_for, so the "f" you are triyng to specify in link_to_add does not hold a value, This line should he moved in line up, so the "end" is after the link

FrankfromDenmark
  • 170
  • 2
  • 12
  • I already have the multipart for the tracks form. I updated the post with the entire _form file. Do you think i should add multipart to the nested form too? – moelgendy Dec 10 '15 at 14:57
  • I don't know, but you wrote `multipart:` its suppose to be `:multipart`, don't know if that helps :) – FrankfromDenmark Dec 10 '15 at 15:23