简体   繁体   中英

Dynamically generated field in nested form added twice Rails

I have two models, the first is grants the second is specs. Specs has two fields ineligibility and eligibility and is nested into grants. I have mostly everything set up fine but I need help modifying the JQuery because every time I click "add an ineligibility", an eligibility is also added. It doesn't show up on the form but it does show up as a blank bullet on my show view. When I go back to edit the form I now see the blank field for eligibility. If I enter new text into eligibility both fields save the correct text. I want to be able to add one field without automatically adding the other. My jQuery and helper code comes from Railscasts PRO #196 Nested Model Form. I'm new to rails and especially jQuery so any help would be greatly appreciated!

jQuery ->
$('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()

and the helper method:

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(name.to_s.singularize + "_fields", f: builder)
    end
    link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
  end

I wanted to share my solution for anyone who might be trying to do the same thing. The mistake I made was thinking that I could have several fields in each model but only save one of those fields to the database. But every time I add a field it saves the whole record with all the other fields even if they are blank. This is why every time I add an eligibility I also get an blank ineligibility field. The solution is to break up the model and create a new model for every field needed.

Since my real goal is just to have bulleted lists of eligibility and ineligibility I came up with two other solutions that simply handle formatting. The first is to use a rich text editor and the other is to use .gsub to add in the formatting after the fact. For example:

<p>
  <strong>Eligibility:</strong>
  <%= (@grant.eligibility).gsub(/[=+~]/, '=' => '<ul>','~' => '</ul>', '+' => '<li/>').html_safe %> 
</p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM