Issues with nested forms - javascript

I'm trying to create a fully manageable website where the user can fill some skills ('css', 'php', 'ruby', you name it). Next to it, they fill how good they think they are with this, in a percentage.
I intend to display the result in graphs but right now I'm stuck with this nested form, I can't make them show up.
So as I said earlier, you can add your skills in a page named settings, so here is how I linked them together:
skill.rb and setting.rb
class Skill < ApplicationRecord
belongs_to :settings, optional: true
end
class Setting < ApplicationRecord
has_many :skills, dependent: :destroy
accepts_nested_attributes_for :skills, allow_destroy: true,
reject_if: proc { |att| att['name'].blank? }
# Other lines...
ApplicationHelper.rb
def link_to_add_row(name, f, association, **args)
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, f: builder)
end
link_to name, '#', class: 'add_fields' + args[:class], data: { id: id, fields: fields.gsub('\n', '') }
end
application.js
$(document).on('turbolinks:load', function() {
$('form').on('click', '.remove_skill', function(event) {
$(this).prev('input[type="hidden"]').val('1');
$(this).closest('div').hide();
return event.preventDefault();
});
$('form').on('click', '.add_fields', function(event) {
let regexp, time;
time = new Date().getTime();
regexp = new RegExp($(this).data('id'), 'g');
$('.skills').append($(this).data('skills').replace(regexp, time));
return event.preventDefault();
});
});
views/settings/_form.html.erb
<!-- Some other fields -->
<table>
<thead>
<tr>
<th></th>
<th>CompƩtence</th>
<th>MaƮtrise</th>
</tr>
</thead>
<tbody class="fields">
<%= fields_for :skills do |builder| %>
<%= render 'skill', f: builder %>
<% end %>
<%= link_to_add_row('Ajouter skill', f, :skills, class: 'add_skill') %>
</tbody>
</table>
<!-- Some other fields -->
**views/settings/_skill.html.erb
<tr>
<td>
<%= f.input_field :_destroy, as: :hidden %>
<%= link_to 'Delete', '#', class: 'remove_record' %>
</td>
<td><%= f.input :name, label: false %></td>
<td><%= f.input :completed, label: false %></td>
<td><%= f.input :due, label: false, as: :string %></td>
</tr>
I followed this video's instruction, and so far when I click on "add skill", I can see my nested form being rendered in my rails console, but that's all.
I think this is just something I didn't see, but I redid the tutorial twice and each time a bit different but nothing shows when i click on "add skill".
Any help is welcomed!

A few things to look at. first, this function:
$('form').on('click', '.add_fields', function(event) {
let regexp, time;
time = new Date().getTime();
regexp = new RegExp($(this).data('id'), 'g');
$('.skills').append($(this).data('skills').replace(regexp, time));
return event.preventDefault();
});
Is looking for an element with a 'skills' class on it and will append the records there. I didn't see an element with it above unless I missed it.
Next, try disabling turbolinks, at least when debugging - I have had problems with that before.
Remove the gem 'turbolinks' line from your Gemfile.
Remove the //= require turbolinks from your app/assets/javascripts/application.js.
Remove the two "data-turbolinks-track" => true hash key/value pairs from your app/views/layouts/application.html.erb.
(from blog.steveklabnik.com/posts/2013-06-25-removing-turbolinks-from-rails-4
After that, throw in a wad of
console.log()
statements in to verify expected values are what you expect, elements exist etc at runtime.
Finally, I have a post about something similar here:
Javascript nested forms for has_many relationships
Which might be of use.

Related

Create dynamic form with has_many (many-to-many) association with a single form in Rails 7

I have 4 models, User, Products, Property & ProductProperty. Here's how they relate:
All attributes in these models, such as name, value, upc, and available_on, must have a presence of value!
Once a user is created successfully, they can create products (with the Products model) that can have many properties (with the Property model) and a corresponding value (with the ProductProperty model). And I have to create all of these in a single form.
With the help of some tutorials and Reddit users, I was able to successfully implement the product form which is able to create a new product, property, and corresponding value. Here's the snap of my implementation:
Now here comes the tricky part: to add more properties dynamically to create multiple properties and their values of a product. So here's my implementation of it so far:
Product Form
<%= form_with model: #product do | prod | %>
<%= prod.label :name %>
<%= prod.text_field :name %>
<br>
<%= prod.label :upc, "UPC" %>
<%= prod.text_field :upc %>
<br>
<%= prod.label :available_on %>
<%= prod.date_field :available_on %>
<br>
<h3>Properties</h3>
<table>
<thead>
<tr>
<th>Property Value</th>
<th>Property Name</th>
</tr>
</thead>
<tbody class="fields">
<%= prod.fields_for :product_properties do | prod_prop | %>
<%= render "property", prod_prop: prod_prop %>
<% end %>
</tbody>
</table>
<br>
<%= link_to_add_fields('Add More Properties', prod, :product_properties) %>
<br>
<%= prod.submit %>
<% end %>
Property Form Partial
<tr>
<td><%= prod_prop.text_field :value %></td>
<%= prod_prop.fields_for :property do | prop | %>
<td><%= prop.text_field :name %></td>
<% end %>
</tr>
Helper Method
def link_to_add_fields(name, prod, association)
new_object = prod.object.send(association).klass.new
id = new_object.object_id
fields = prod.fields_for(association, new_object, child_index: :id) do | builder |
render "property", prod_prop: builder
end
link_to(name, "#", class: 'add_fields', data: {id: id, fields: fields.gsub("\n", "") } )
end
application.js file:
$("form").on("click", ".add_fields", function (event) {
let regexp, time;
time = new Date().getTime();
regexp = new RegExp($(this).data("id"), "g");
$(".fields").append($(this).data("fields").replace(regexp, time));
return event.preventDefault();
});
Now when I click on the "Add more Properties" link it adds only one field:
Issue 1: I believe I need to do some modifications in the helper method to implement this correctly but I am not able to figure out the logic of it.
There's one more issue! When we create additional property instances of property name & value, they will all disappear if there're any validation errors:
Product Controller:
def new
#product = Product.new
#product.product_properties.build.build_property
end
def create
#product = current_user.products.new(product_params)
if #product.valid?
#product.save
redirect_to products_path, notice: "Success!"
else
render 'new', status: :unprocessable_entity
end
end
I can think of a couple of solutions to this issue: first, to implement the logic in the create action for the dynamically created property name and value fields to persist between requests, second, to use javascript.
Issue 2: So how do I make the additional properties created by the user persist in the view between requests?
I am running rails v7.0.4 and I am not allowed to use hotwire, only Javascript.

Save two models (which belong_to a third model) with one submit?

When the user clicks submit how can the info from two different models/DB tables be passed?
The user should be able to create a note in the missed_dates form and then that note should be saved to the respective #challenge the missed date is referring to.
missed_dates/form.html.erb
<%= simple_form_for(#missed_date, url: challenge_missed_dates_path({ routine_id: #challenge }), remote: request.xhr?, html: { data: { modal: true } }) do |a| %>
<%= form_for [#notable, #note] do |b| %>
<%= a.text_field :one %>
<%= b.text_field :two %>
<%= button_tag(type: 'submit') do %>
Save
<% end %>
<% end %>
<% end %>
missed_date.rb
class MissedDate < ActiveRecord::Base
belongs_to :user
belongs_to :challenge
end
missed_date_controller
def new
#challenge = current_user.challenges.find(params[:challenge_id])
#missed_date = current_user.missed_dates.build
#notable = #challenge
#note = Note.new
end
def create
challenge = current_user.challenges.find(params[:challenge_id])
challenge.missed_days = challenge.missed_days + 1
challenge.save
#missed_date = challenge.missed_dates.build(missed_date_params)
#missed_date.user = self.current_user
#missed_date.save
respond_modal_with #missed_date, location: root_path
flash[:alert] = 'Strike added'
end
Short: use "belongs_to" and "has_many :through" association between Note and MissedDates. Then you can use nested attributes.
Long version: This in probably an issue of an improper or incomplete structure of your models. Usually, you can use nested attributes (see http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html) to achieve this.
But, this implies that the models have a direct relation. You should consider if you can do a belongs_to/has_many relation between the note and the missed_date model. This could be done e.g. by "has_many :through..." (http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association) without changing your current db scheme.

How to Change Date Format According to User Selection?

How can I change the date :order according to the User's "f.select :categories" choice?
For example when a User goes to the Quantified _form he can select between "Monthly Average" or "One-Time Instance";
If he selects "Monthly Average" I want the _results_fields.html.erb to provide the date selection as ":order => [:month, :year]" if he selects "One-Time Instance" I want the _results_fields.html.erb to provide the date selection as ":order => [:month, :day, :year]
Ideally this would be done dynamically via javascript, but I would be happy to accept an answer that does it via the view.
_results_fields.html.erb
<div class="nested-fields">
<div class="form-group">
<%= f.text_field :result_value, class: 'form-control', placeholder: 'Enter Result' %>
<br/>
<%= f.date_select :date_value, :order => [:month, :year], class: 'date-select' %>
<%= link_to_remove_association "Remove Result", f %>
</div>
</div>
_form.html.erb
<%= form_for #quantified do |f| %>
<div class="america">
<%= f.select :categories, Quantified::CATEGORIES %>
<br/>
<br/>
<div class="form-group">
<%= f.text_field :name, class: 'form-control', placeholder: 'Enter Name' %>
</div>
<div class="form-group">
<%= f.text_field :metric, class: 'form-control', placeholder: 'Enter Metric' %>
</div>
<div id="results">
<%= f.fields_for :results do |result| %>
<%= render 'result_fields', :f => result %>
<% end %>
</div>
<div class="links">
<%= link_to_add_association 'add result', f, :results %>
</div>
<%= f.submit %>
</div>
<% end %>
quantified.rb
class Quantified < ActiveRecord::Base
belongs_to :user
scope :averaged, -> { where(categories: 'Monthly Average') }
scope :instance, -> { where(categories: 'One-Time Instance') }
has_many :results
accepts_nested_attributes_for :results, :reject_if => :all_blank, :allow_destroy => true
CATEGORIES = ['Monthly Average', 'One-Time Instance']
end
Github: https://github.com/RallyWithGalli/ruletoday
Thank you for your time.
The answer here was to use some jquery provided by the gem that was being used to add the date selects, as well as some jquery of our own
First things first, we rig up the checkboxes with a click() event, that hides anything with the class 'day' if instance is checked, and shows it if not.
$('.date-toggle').click(function(){
if( $(this).attr('id') == 'instance') {
$('.day').show();
} else {
$('.day').hide();
}
});
The trick here is to use the rails date select option :with_css_classes on the date select, so that it looks like this:
<%= f.date_select :date_value, :order => [:month, :day, :year], :with_css_classes => true, class: 'date-select' %>
This causes each included field to get a class corresponding to its name, hence our reference to '.day' up there.
The next important part, however, because he is using a gem called cocoon to add new elements that included date fields, we had to use some of their jquery event bindings to make sure that the new ones got the right action applied to them.
$('#container').on('cocoon:after-insert', function(e, insertedItem) {
if($('#instance').is(':checked')) {
$('.day').show();
} else {
$('.day').hide();
}
});
Technically, the $('.day').show() is not necessary, because it defaults to being shown, but this, to me, gets across the intent a little clearer.
I think my solution is a little bit messy, but hopefully it gives you an indication of my train of thought and give you something to build upon.
I have changed your categories to work with a radio button group because the select field is a bit weird for 2 elements (subjective I know), to change it back to a select form,simply keep your code as is, but you will need to check the value of the select dropdown using jQuery .change() or some other vanilla Javascript way...
You haven't provided any controller names, so I didn't know how to name my JS file, but hopefully you know how to integrate.
IMO, I'm not sure why this needs AJAX, so maybe you can explain to me where that comes in.
_form.html.erb
<%= Quantified::CATEGORIES.each do |c| %>
<%= f.radio_button(:category, c) %>
<%= label(c, c) %>
<% end %>
_results_fields.html.erb
<%= f.date_select :date_value, :order => [:month, :year], class: 'date-select-my' %>
<%= f.date_select :date_value, :order => [:month, :year], class: 'date-select-mdy' %>
vanilla.js
$(document).ready(function(){
$('.date-select-mdy').hide();
$('.date-select-mdy').attr("disabled", true);
$('input[name$=\category\']').click(function() {
var target_value;
target_value = $(this).val;
if (target_value === 'Monthly Average') {
$('.date-select-my').show();
$('.date-select-mdy').hide();
$('.date-select-my').attr("disabled", false);
return $('.date-select-mdy').attr("disabled", true);
} else {
$('.date-select-my').hide();
$('.date-select-mdy').show();
$('.date-select-my').attr("disabled", true);
return $('.date-select-mdy').attr("disabled", false);
}
});
});
a_little_bit_of_coffee_because_i_dislike_js.coffee
$->
$('.date-select-mdy').hide()
$('.date-select-mdy').attr("disabled",true)
$('input[name$=\category\']').click ->
target_value = $(this).val
if target_value == 'Monthly Average'
$('.date-select-my').show()
$('.date-select-mdy').hide()
$('.date-select-my').attr("disabled",false)
$('.date-select-mdy').attr("disabled",true)
else
$('.date-select-my').hide()
$('.date-select-mdy').show()
$('.date-select-my').attr("disabled",true)
$('.date-select-mdy').attr("disabled",false)
return

Adding Forms Dynamically From Dropdown Menu Selection

I have a Ruby on Rails question about adding a dynamic form through a drop down selection rather than having individual buttons for each possible selection.
Right now, through the help of following some Railscasts, my application works where I have three individual buttons that are able to dynamically add three different types of nested forms to the parent, all corresponding to different models with different form partials.
The parent model here is a Workout, allowing traditional_blocks, emon_blocks, and tempo_blocks to be added dynamically using JS.
Workout Model
class Workout < ActiveRecord::Base
has_many :tempos
has_many :traditionals
has_many :emons
accepts_nested_attributes_for :tempos, allow_destroy: true
accepts_nested_attributes_for :emons, allow_destroy: true
accepts_nested_attributes_for :traditionals, allow_destroy: true
end
/app/views/workouts/new.html.erb
<div>
<%= button_to_add_fields "Add EMON Block", f, :emons %>
<%= button_to_add_fields "Add traditional Block", f, :traditionals %>
<%= button_to_add_fields "Add tempo Block", f, :tempos %>
</div>
/apps/helpers/application_helper.rb
module ApplicationHelper
def button_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
button_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
end
end
app/assets/javascripts/workouts.js.coffee
$(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 I said earlier, everything works as I want it to when I click the buttons. However, I would like to be able to put "emon block, traditional block, tempo block" inside a collection_select with one button next to the collection_select that says "create." When that "create" button is clicked, I would like it to call that same helper(button_to_add_fields) passing along the necessary parameters for it to work the same way it does now with the multiple button implementation but using the currently selected association in the collection select.
Any tips?
You'll want to use Ajax for this
The Railscast you viewed, although helpful, is somewhat limited in the way that it will only allow you to add a single nested form each time
--
Ajax
#config/routes.rb
resources :workouts do
get "ajax_fields/:type", on: :collection
end
#app/models/workout.rb
Class Workout < ActiveRecord::Base
...
def self.build type
workout = self.new
if type
workout.send(type).build
else
workout.tempos.build
workout.traditionals.build
workout.emons.build
end
end
end
#app/controllers/workouts_controller.rb
Class WorkoutsController < ApplicationController
def ajax_update
#workout = Workout.build params[:type]
render "form", layout: !request.xhr?
end
end
#app/views/workouts/_form.html.erb
<%= form_for #workout do |f| %>
<%= render "fields", locals: { f: f }, onject: params[:type] %>
<%= f.submit %>
<% end %>
#app/views/workouts/_fields.html.erb
<%= f.fields_for type.to_sym, child_index: Time.now.to_i do |t| %>
<%= t.text_field :your_field %>
<% end %>
#app/views/workouts/new.html.erb
<%= form_for #workout do |f| %>
<%= render: "fields", locals: { f: f}, collection: ["tempos", "traditionals", "emons"], as: :type %>
<%= ... dropdown code ...%>
<%= f.submit %>
<% end %>
--
This will allow you to send the following ajax request:
#app/assets/javascripts/workouts.js.coffee
$(document).on 'change', 'form .add_fields', (event) ->
type = $(this).val
$.ajax
url: "/workouts/ajax_fields/" + type,
success: function(data) {
$("form").append(data); // will have to work this out properly
}
});
This should give you the ability to append the extra fields you need to the application, which will then come back with the appropriate HTML for you to append to your DOM
Hopefully you can appreciate the sentiment here - it might not work right out of the box!

Using JQuery to Generate Nested Objects in One Form in Rails 4

Using Rails 4, and based on Railscast #197 I'm trying to create both parent and child objects using a single form dynamically via Javascript. I've modified Ryan Bate's code in his application helper (on the same page as the railscast episode) so that I can create both a parent object (BudgetSegment) and child object (BudgetRatio) in one form.
I'd like someone to take a look at my link_to_add_fields method below and tell me what is wrong, as it is not working, AND to tell me if it is the culprit for the feature not working. Could it be that you can't nest the builder.fields.forin the f.fields_for block below? Here is the relevant code in application_helper.rb:
def link_to_add_fields(name, f, association, nested_association, locals={})
new_object = f.object.class.reflect_on_association(association).klass.new
nested_new_object = f.object.class.reflect_on_association(association).klass.reflect_on_association(nested_association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
builder.fields_for(nested_association, nested_new_object, :child_index => "new_#{nested_association}") do |nested_builder|
render(association.to_s.singularize + "_row", locals.merge!(:ff => builder, :fff => nested_builder))
end
end
link_to_function(name, "add_fields(this, \"#{association}\", \"#{nested_association}\", \"#{escape_javascript(fields)}\")")
end
Here is my js file:
function add_fields(link, association, nested_association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g")
var regexp2 = new RegExp("new_" + nested_association, "g")
$(link).parent().parent().parent().before().child(content.replace(regexp, new_id).replace(regexp2, new_id);
}
Both BudgetSegment and BudgetRatio are on the same row of a table. the goal is to allow the user to dynamically create a new row of text fields upon clicking an add button. This row would concurrently create both a BudgetSegment text field in the first column and an indeterminate number of BudgetRatio text fields in the columns to the right(for the Javascript method, I'm only assuming one BudgetRatio is created, although as you will see in the budget_source_controller, there are five BudgetRatios created initially).
This link_to_add_fields code should be generating the following partial _budget_segment_row.html.erb below:
<tr class="table-financial">
<td><%= ff.text_field :max, :id => "form-currency", :class => "form-control", :placeholder => '"$1,000,000"', :required => :true %>
</td>
<%= ff.fields_for :budget_ratios do |fff| %>
<td><%= fff.text_field 'box_value', :class => "form-control", :placeholder => 'e.g., "0.75"' %></td>
<td><%= fff.text_field 'pa_value', :id => "pa-value", :class => "form-control", :placeholder => 'e.g., "0.75"' %></td>
<% end %>
</tr>
When I debug, the fieldsvariable defined in link_to_add_fields at the top does not return the child (BudgetRatio), only the parent (BudgetSegment). Below is what fields returns:
"<tr class=\"table-financial\">\n\t<td><input class=\"form-control\" id=\"form-currency\" name=\"budget_source[budget_segments_attributes][new_budget_segments][max]\" placeholder=\""$1,000,000"\" required=\"required\" type=\"text\" />\n\t</td>\n\t\t\n\t\t</tr>"
As you can see, anything in the BudgetRatio block is missing.
Here is my model structure (relevant parts included only):
class BudgetSource < ActiveRecord::Base
has_many :budget_segments
accepts_nested_attributes_for :budget_segments
end
class BudgetSegment < ActiveRecord::Base
has_many :budget_ratios
accepts_nested_attributes_for :budget_ratios
end
class BudgetRatio < ActiveRecord::Base
belongs_to :budget_segment
end
Below is new.html.erb for BudgetSource (a few irrelevant parts omitted):
<div class="container">
<div class="info-box">
<%= form_for #budget_source, :method => :post, :url => budget_sources_path do |f| %>
<%= render 'tag_menu_new', :f => f %>
<%= f.fields_for :budget_segments do |ff| %>
<div class="table-responsive">
<table class="table table-condensed table-hover">
<tr class="table-sources-heading">
<th rowspan="2">Budget Segment Maximum</th>
<% scenarios.each do |s| %>
<th colspan="2"><%= s.name %></th>
<% end %>
<th rowspan="2">add</th>
</tr>
<tr class="table-sources-heading">
<% scenarios.each do |s| %>
<th><%= "Box Ratio" %></th>
<th><%= "P&A Ratio" %></th>
<% end %>
</tr>
<%= render 'budget_segment_row', {f: f, ff: ff} %>
<tr>
<td><div class="btn btn-default"><%= link_to_add_fields "Add Row", f, :budget_segments, :budget_ratios, :f => f %></td>
</tr>
</table>
</div>
<% end %>
</div>
<div class="row">
<div class='col-sm-6 col-sm-offset-3'>
<%= f.submit 'Save', :class => "btn btn-success" %>
</div>
</div>
</div>
<% end %>
</div>
Below is budget_sources_controller.rb:
class BudgetSourcesController < ApplicationController
include ApplicationHelper
require 'debugger'
def new
#budget_source = BudgetSource.new
2.times { #budget_source.budget_sources_genres.build }
#budget_segment = #budget_source.budget_segments.build
scenarios.count.times { #budget_segment.budget_ratios.build }
render 'budget_sources/new'
end
def create
#budget_source = BudgetSource.create(budget_source_params)
#budget_source.update(:user_id => current_user.id)
#budget_source.budget_segments.order(:id).each do |bs|
bs.budget_ratios.order(:id).each_with_index do |br, i|
br.update(scenario_id: i+1)
end
end
render 'show'
end
def show
#budget_source = BudgetSource.find(params[:id])
render 'show'
end
private
def budget_source_params
params.require(:budget_source).permit(:id, :user_id, :name, :description, :territory_id, budget_sources_genres_attributes: [:id, :genre_id, :budget_source_id], budget_segments_attributes: [:id, :max, budget_ratios_attributes: [:id, :box_value, :pa_value, :budget_segment_id, :scenario_id]])
end
end
Well this might not solve your problem, but it'll help with readability at least. Try doing this:
new_object = f.const_get(association).new
nested_new_object = f.const_get(nested_association).new
# new_object = f.object.class.reflect_on_association(association).klass.new
# nested_new_object = f.object.class.reflect_on_association(association).klass.reflect_on_association(nested_association).klass.new
However, i think what might be the issue is you are passing in fff: fff
locals.merge!(:ff => builder, :fff => nested_builder))
and the only place you're using fff that I can see is inside this block:
<%= ff.fields_for :budget_ratios do |fff| %>
<td><%= fff.text_field 'box_value', :class => "form-control", :placeholder => 'e.g., "0.75"' %></td>
<td><%= fff.text_field 'pa_value', :id => "pa-value", :class => "form-control", :placeholder => 'e.g., "0.75"' %></td>
<% end %>
but as you know, the fff inside the block isn't the fff that youre passing. Might not be the error, but looks like it could be an oversight. Maybe you meant to merge in f and ff
Also, here's an example of a triple nested form that added new items to an even in a table. Might help to look at:
Here's the javascript we used to add/remove items.
https://github.com/alukima/TooManyChips/blob/master/app/assets/javascripts/add_item.js
events' create view:
https://github.com/alukima/TooManyChips/blob/master/app/views/events/_create_event_form.html.erb
and partial for add_items at the bottom, which had the 3rd nesting in it.
https://github.com/alukima/TooManyChips/blob/master/app/views/event_items/_create_event_items_form.html.erb
Although this wasn't quite the solution I wanted (I really wanted to know why you're not able to nest an object using builder), my quick fix was:
Rather than nesting a f.fields_for method inside a fields_for do |f| block (as is conventional in views), I created a nested object by using the [object].object.association.build method.
You'll note a new line starting with array because I wanted to create a defined number of objects at the same time, so I passed an iterator variable into the method that is basically just a integer. Here's my revised link_to_add_fields code:
def add_row(name, f, association, nested_association, iterator)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, child_index: "new_#{association}") do |bs|
array = eval("iterator.map {bs.object.#{nested_association}.build}")
render(association.to_s.singularize + "_row", {f: f, ff: bs, fff: array})
end
link_to_function(name, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
end

Categories

Resources