Coder Social home page Coder Social logo

nested_form's Introduction

Unmaintained

The Nested Form gem is no longer maintained. Feel free to fork this project.

Nested Form

Build Status

This is a Rails gem for conveniently manage multiple nested models in a single form. It does so in an unobtrusive way through jQuery or Prototype.

This gem only works with Rails 3. See the rails2 branch for a plugin to work in Rails 2.

An example project showing how this works is available in the complex-nested-forms/nested_form branch.

Setup

Add it to your Gemfile then run bundle to install it.

gem "nested_form"

And then add it to the Asset Pipeline in the application.js file:

//= require jquery_nested_form

Non Asset Pipeline Setup

If you do not use the asset pipeline, run this generator to create the JavaScript file.

rails g nested_form:install

You can then include the generated JavaScript in your layout.

<%= javascript_include_tag :defaults, "nested_form" %>

Usage

Imagine you have a Project model that has_many :tasks. To be able to use this gem, you'll need to add accepts_nested_attributes_for :tasks to your Project model. If you wish to allow the nested objects to be destroyed, then add the :allow_destroy => true option to that declaration. See the accepts_nested_attributes_for documentation for details on all available options.

This will create a tasks_attributes= method, so you may need to add it to the attr_accessible array (attr_accessible :tasks_attributes).

Then use the nested_form_for helper method to enable the nesting.

<%= nested_form_for @project do |f| %>

You will then be able to use link_to_add and link_to_remove helper methods on the form builder in combination with fields_for to dynamically add/remove nested records.

<%= f.fields_for :tasks do |task_form| %>
  <%= task_form.text_field :name %>
  <%= task_form.link_to_remove "Remove this task" %>
<% end %>
<p><%= f.link_to_add "Add a task", :tasks %></p>

In order to choose how to handle, after validation errors, fields that are marked for destruction, the marked_for_destruction class is added on the div if the object is marked for destruction.

Strong Parameters

For Rails 4 or people using the "strong_parameters" gem, here is an example:

params.require(:project).permit(:name, tasks_attributes: [:id, :name, :_destroy])

The :id is to make sure you do not end up with a whole lot of tasks.

The :_destroy must be there so that we can delete tasks.

SimpleForm and Formtastic Support

Use simple_nested_form_for or semantic_nested_form_for for SimpleForm and Formtastic support respectively.

Partials

It is often desirable to move the nested fields into a partial to keep things organized. If you don't supply a block to fields_for it will look for a partial and use that.

<%= f.fields_for :tasks %>

In this case it will look for a partial called "task_fields" and pass the form builder as an f variable to it.

Specifying a Target for Nested Fields

By default, link_to_add appends fields immediately before the link when clicked. This is not desirable when using a list or table, for example. In these situations, the "data-target" attribute can be used to specify where new fields should be inserted.

<table id="tasks">
  <%= f.fields_for :tasks, :wrapper => false do |task_form| %>
    <tr class="fields">
      <td><%= task_form.text_field :name %></td>
      <td><%= task_form.link_to_remove "Remove this task" %></td>
    </tr>
  <% end %>
</table>
<p><%= f.link_to_add "Add a task", :tasks, :data => { :target => "#tasks" } %></p>

Note that the :data option above only works in Rails 3.1+. For Rails 3.0 and below, the following syntax must be used.

<p><%= f.link_to_add "Add a task", :tasks, "data-target" => "#tasks" %></p>

JavaScript events

Sometimes you want to do some additional work after element was added or removed, but only after DOM was really modified. In this case simply listening for click events on 'Add new'/'Remove' link won't reliably work, because your code and code that inserts/removes nested field will run concurrently.

This problem can be solved, because after adding or removing the field a set of custom events is triggered on this field. Using form example from above, if you click on the "Add a task" link, nested:fieldAdded and nested:fieldAdded:tasks will be triggered, while nested:fieldRemoved and nested:fieldRemoved:tasks will be triggered if you click "Remove this task" then.

These events bubble up the DOM tree, going through form element, until they reach the document. This allows you to listen for the event and trigger some action accordingly. Field element, upon which action was made, is passed along with the event object. In jQuery you can access it via event.field, in Prototype the same field will be in event.memo.field.

For example, you have a date input in a nested field and you want to use jQuery datepicker for it. This is a bit tricky, because you have to activate datepicker after field was inserted.

jQuery

$(document).on('nested:fieldAdded', function(event){
  // this field was just inserted into your form
  var field = event.field;
  // it's a jQuery object already! Now you can find date input
  var dateField = field.find('.date');
  // and activate datepicker on it
  dateField.datepicker();
})

Prototype

document.observe('nested:fieldAdded', function(event){
  var field = event.memo.field;
  // it's already extended by Prototype
  var dateField = field.down('.date');
  dateField.datepicker();
})

Second type of event (i.e. nested:fieldAdded:tasks) is useful then you have more than one type of nested fields on a form (i.e. tasks and milestones) and want to distinguish, which exactly was added/deleted.

See also how to limit max count of nested fields

Enhanced jQuery JavaScript template

You can override default behavior of inserting new subforms into your form. For example:

window.nestedFormEvents.insertFields = function(content, assoc, link) {
  return $(link).closest('form').find(assoc + '_fields').append($(content));
}

Contributing

If you have any issues with Nested Form not addressed above or in the example project, please add an issue on GitHub or fork the project and send a pull request. To run the specs:

bundle install
bundle exec rake spec:install
bundle exec rake db:migrate
bundle exec rake spec:all

See available rake tasks using bundle exec rake -T.

Special Thanks

This gem was originally based on the solution by Tim Riley in his complex-form-examples fork.

Thank you Andrew Manshin for the Rails 3 transition, Andrea Singh for converting to a gem and Peter Giacomo Lombardo for Prototype support.

Andrea also wrote a great blog post on the internal workings of this gem.

Thanks Pavel Forkert for the SimpleForm and Formtastic support.

nested_form's People

Contributors

amatsuda avatar andrewshawcare avatar baltazore avatar basvanwesting avatar cdemyanovich avatar derekprior avatar dmarkow avatar dougfarre avatar eljuanchosf avatar eric88 avatar fxposter avatar ghostganz avatar grk avatar harrigan avatar jipiboily avatar lest avatar madebydna avatar mgreenly avatar mhuggins avatar michaelglass avatar nashbridges avatar nashby avatar nhocki avatar nickhoffman avatar pellegrino avatar rvanlieshout avatar ryanb avatar sunny avatar taavo avatar tricknotes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nested_form's Issues

Working with nested attributes and acts_as_list

I have a slightly unusual requirement that means I need to respect acts_as_list positions when adding/removing nested models.

class Journey < ActiveRecord::Base
  has_many :legs, :dependent => :destroy
  accepts_nested_attributes_for :legs, :allow_destroy => true
end

class Leg < ActiveRecord::Base
  belongs_to :journey
  acts_as_list :scope => :journey
end

I don't think this is that odd - the legs of my journey have a destination, and the order of them determines the start and end points.

Of course, this means I can't use the standard helpers of f.link_to_add and f.link_to_remove as these are form level helpers, and I want a helper to sit with the nested form. I can handle the JS to update positions of subsequent legs no problem, but I was wondering if there was an established way of doing this already, or whether I need to fork, build new helpers and then issue a pull request? I was thinking something like being able to do a:

  <%= f.link_to_add_inline "Add leg", :legs, :after => current_leg.position %>

Thoughts?

Improve tests

The tests need a lot of work. They should be changed to use RSpec request specs with Capybara and a sample Rails app. This way I can mimic the functionality and test JavaScript too.

Possibility to add multiples fields

Hi Ryan !
I liked very much you gem, all works as a charm. But I wonder if it is possible to generate/add more than 1 nested textfield at a time. For example, as for the screencast 197, I'd like to add 3 questions with 3 answers, not one by one. Is it possible to pass a counter value somehow to the helper method you used?
Thanks in advance.

unknown attribute error when submitting multiple records in double-nested form

I'm using nested_form for a situation where:

Parent (climb) ==has_one==> Join Model (route_ascent) ==polymorphic has_many==> Children (route_step)

So I have a climb object that looks like

class Climb < ActiveRecord::Base
  has_one :route_ascent
  accepts_nested_attributes_for :route_ascent
end

Here's RouteAscent

class RouteAscent < ActiveRecord::Base
  has_many :ascent_steps, :class_name => 'RouteStep', :as => :steppable
  accepts_nested_attributes_for :ascent_steps, :allow_destroy => true
end

And Here's RouteStep

class RouteStep < ActiveRecord::Base
  belongs_to :steppable, :polymorphic => true
end

In my Climb form I have

f.fields_for :route_ascent

My _route_ascent_fields partial is simply

<%= f.fields_for :ascent_steps %>
<p><%= f.link_to_add "Add A Step", :ascent_steps %></p>

And my _ascent_step_fields partial is

<div class="field">
<%= f.label :order %>
<%= f.text_field :position %><br>
<%= f.label :description %>
<%= f.text_area :description %>
<%= f.link_to_remove "Remove Step" %>
</div>

The problem I have is that whenever I submit the form with more than one object in the join model's has_many association, I get an unknown attribute error. Here's what the parameters look like that are generated by the form in such a case:

"route_ascent_attributes"=>{"ascent_steps_attributes"=>{"0"=>{"position"=>"1",
 "description"=>"this will also work",
 "_destroy"=>"false",
 "id"=>"66"}},
 "0"=>{"new_1307386880995"=>{"position"=>"2",
 "description"=>"broken!",
 "_destroy"=>"false"}},
 "id"=>"4"},

It looks like the second object is not being included correctly in the parameters, but I haven't been able to figure out why this is so.

The problem occurs whether or not the has_many association starts out with an object or not. So If it is empty, I can successfully create a single object but not two. If It already has one object, I can't add a second without getting this error.

Will continue to work on this, but I'd appreciate any insight as to what the problem might be!

Add link doesnt work with HAML

I've worked all day long with the plugin. It worked perfectly with html.erb files. Changed to Haml and everything rendered fine but the add link doesnt work.

Check the generated code in html.erb after comes the blueprint div with the reference code. That div is empty if I use Haml.

I think the problem is in link_to_add inside the builder around here

@template.concat(%Q[

])
fields_for(association, model_object, :child_index => "new_#{association}", &@fields[association])
@template.concat('
')

Tried without success to put a debugger and run the fields_for to see what was generated. Seems like because of the way HAMLS renders this fields_for returns nothing when called. Maybe because it's already past the end of the form since there if no explicit <%end%> in HAML.

Solved the problem removing Haml in the parts where de add link appears in something like this:

<% nested_form_for [@Portfolio, project], :html => {:multipart => true} do |f| %>
<%= render :partial => 'projects/globals_form', :locals => { :f => f } %>
<% #This render will show once for every asset automatically
f.fields_for :asset do |a| %>
<%= render :partial => 'projects/assetsform', :locals => { :a => a }%>
<% end %>

<p style="clear: both"> <%= f.link_to_add "Add a new Asset", :assets  %> </p>
<p style="clear: both"> <%= f.submit 'Update'%> </p>

<%end%>

Those partials are written in HAML but the add link must be inside the html.erb. Sorry, I tried to solve the issue but if you know what to do next do would be really useful.

Breaks client_side_validations

Gemfile:
gem 'jquery-rails'
gem 'client_side_validations'
gem 'nested_form'

_form.html.erb:

form_for(@project, :validate => true) do |f|
... WORKS

nested_form_for(@project, :validate => true) do |f|
... no longer does client side validation.

Missing Block error when using link_to_add

When I include the link_to_add method in my nested_form_for block, I get a Missing Block error. Here's the relevant part of my template:

<%= nested_form_for group do |form| %>
    <%= form.label :name, "Name" %>
    <%= form.text_field :name, :class => "text-input" %>
    <%= form.fields_for :habitats do |ff| %>
        <%= content_tag :div, :class => "fields" do %>
        <%= ff.text_field :name, :class => "text-input" %>
            <%= ff.link_to_remove "Remove Habitat" %>
        <% end %>
    <% end %>
    <%= form.link_to_add "Add Habitat", :habitats%>
<% end %>

The error is tied to the first line of the above code, but it only occurs when I include the link_to_add line (second to last). Here's the trace:

actionpack (3.0.5) lib/action_view/helpers/form_helper.rb:531:in `fields_for'
actionpack (3.0.5) lib/action_view/helpers/form_helper.rb:1175:in `fields_for'
nested_form (0.1.0) lib/nested_form/builder.rb:8:in `link_to_add'
nested_form (0.1.0) lib/nested_form/view_helper.rb:8:in `call'
nested_form (0.1.0) lib/nested_form/view_helper.rb:8:in `nested_form_for'
nested_form (0.1.0) lib/nested_form/view_helper.rb:7:in `map'
nested_form (0.1.0) lib/nested_form/view_helper.rb:7:in `nested_form_for'

I've looked at the actionpack and nested_form source involved here, but I can't see the problem.

link_to_remove not hiding objects

Hi there!

Don't know the reason, but the gem jquery it's not working properly. It let's me add an object dynamically to the form, but the problem is on the link_to_remove function. It let's me delete the objects if I click on the link and then submit the form. But they are not hiding.

This only happens on the previous saved objects, not on the recently added on the form using "link_to_add" function.

I'm using rails 3.0.9 and jQuery 1.6.1

Here is the pastie of the models and the view
http://pastie.org/2214259

Wrong names/IDs for some doubly nested forms

Here's a skeletal example. Model relations:

User has_many :projects
Project has_many :tasks

Simple form:

= nested_form_for(@user) do |f|
  .projects
    = f.fields_for :projects do |pf|
      .tasks
        = pf.fields_for :tasks do |tf|
          = tf.text_field :description
          = tf.link_to_remove 'Remove this task'
        = pf.link_to_add 'Add a task', :tasks
      = pf.link_to_remove 'Remove this project'
    = f.link_to_add 'Add a project', :projects
  = f.submit

If you click 'Add a project' and then 'Add a task', you'll get an input with a name like user[projects_attributes][new_1306716504432][tasks_attributes][new_1306716506218][description]. If you click 'Add a task' again, you'll get another input with exactly the same name.

The IDs won't be exact duplicates. The first and second IDs in this test run were:

user_projects_attributes_new_1306716504432_projects_tasks_attributes_new_1306716506218_description
user_projects_attributes_new_1306716504432_projects_tasks_attributes_new_1306716506218_tasks_description

I think the problem is this line in nested_form.js:

var context = ($(this).closest('.fields').find('input:first').attr('name') || '').replace(new RegExp('\[[a-z]+\]$'), '');

If I had a text field for the project name before the nested tasks, then input:first would be the project name, and the context would be the project. But I don't, and so input:first is the hidden "destroy project" input. But the second time I add a task, input:first is the description field for the first project.

It may also be that this line is fine, and the subsequent code is trying to be smart about handling a context that could be either "the surrounding object" or "an existing sibling of the new object", but getting it wrong. I haven't dug into that code yet.

If I change the selector from input:first to input:last, it works for me, because it always picks up the "destroy project" input. But if the "Remove this project" link were above the tasks instead of below it, it would break the same way it's breaking for me now.

I guess another workaround is just to put the remove link above the associations. But unfortunately in my real use case, there is no remove link, and the context seizes on some other input. I suspect there's just an inherent brittleness to this method of using existing inputs to figure out context.

I'm using the master branch at 89953fa.

Potential clash between an existing ID and the randomly generated ID

Hello,
this is more a concern than an issue.

I'm wondering what happens if the ID generated by:
var new_id = new Date().getTime();
content = content.replace(regexp, new_id);
end up being an existing record id in the DB. Wouldn't it be mistakenly erased by this new record?

ActiveRecord::NestedAttributes::TooManyRecords error

Quikly. When I have in my model:

accepts_nested_attributes_for :foofoo, :allow_destroy => true, :limit => 2

When I do the next I get the error. But it shouldn't show because only one FooFoo is submiting and the limit is 2. Althought I delete the FooFoo, when I overcome the limit, althought I delete the rest before of submit the form, I get the error.

Add FooFoo x 3
Delete FooFoo x 2
Submit Form

Any help?

jQuery is not defined jQuery(function($) {

Hi, I'm using nested_form and jquery-rails (https://github.com/indirect/jquery-rails) but it's not working for me

This is my form:

<%= nested_form_for(@project, :html => {:multipart => true}) do |f| %>
Project Name:

<%= f.text_field :name %>

What do you want us to build for you?

<%= f.text_area :description %>

<%= f.fields_for :images do |image_task| %>
Upload:

<%= image_task.file_field :file %>

<% end %>
<%= f.link_to_add "Add a image", :images %>
<%= f.submit %>
<% end %>

tinymce_hammer fields

I have run into a problem while trying to use tinymce for one of my nested fields. I am using jQuery and I believe the issue is that

$('form a.add_nested_fields').live('click', function() {
//...
  var content = $('#' + assoc + '_fields_blueprint').html(); // Fields template

the html method call to pull in the content is not pulling in tinymce's iframe html. This is to be expected, but I cannot figure out a good way to pull everything from the fields blueprint into the content var. Note: the fields blueprint does appear correctly on the page with the iframe fully populated.

Example jquery event use needed for readme

So this one is a bit selfish...

I think it'd be nice to have some sample code on how to utilize the jquery events (i.e. nested.fieldAdded) to access the fields that were added. I'm a JS/jquery n00b and I'm slogging my way through it now. If I get it working, I'll add a sample myself. Otherwise, I'll hope someone else beats me to it.

I'm attempting to bind a jqueryui datepicker to any fields that are added that have the class datepicker.

leftover "removed" fields make trouble for client-side validation

If you add an item, get its inputs into an invalid state (e.g., by leaving a required field blank), and then remove the item, client_side_validations (and probably other client-side validation solutions) will still flag the now-hidden fields as invalid, but the user has no way to "correct" them.

I can work around this from the validation side, but I'm thinking, is there any reason to keep the .fields around once an element is removed? What if we just remove it, or replace it with the hidden 'destroy' input if there is one?

HTML5 Validation in Hidden Fields

The hidden fields are being validated by the parameter (required = "required") in HTML5.

could remove the parameter when the field is hidden !

Thank's

Gotcha: Clarification required in the README example

The way in which the 'link_to_add' helper is used in the example led to a small issue. The nested_form.js file has this on line #34:
$(this).parent().before(content);

This will insert a new child properly.

However, if you are updating an existing parent model that already has a child defined, and you add another child, this added the new fields above the existing child records.

Wrapping the 'add' link in another element fixed this. So, instead of:
<% f.fields_for :tasks do |task_form| %>
<%= task_form.text_field :name %>
<%= task_form.link_to_remove "Remove this task" %>
<% end %>
<%= f.link_to_add "Add a task", :tasks %>

Use:
<% f.fields_for :tasks do |task_form| %>
<%= task_form.text_field :name %>
<%= task_form.link_to_remove "Remove this task" %>
<% end %>

<%= f.link_to_add "Add a task", :tasks %>

Cheers.

in Rails 3.1.rc1 wrong number of arguments (4 for 3) occured

here is the correct one

module NestedForm
class Builder

def fields_for_with_nested_attributes(association_name, association, options, block)
  block ||= Proc.new { |fields| @template.render(:partial => "#{association_name.to_s.singularize}_fields", :locals => {:f => fields}) }
  @fields ||= {}
  @fields[association_name] = block
  super(association_name, association, options, block)
end

end
end

NestedForm in rails 3.0.0beta4

The nested_form_for method does not seem to be able to render the fields from that model.
The output that I get from the form is just raw html, no fields, like so:

[#]

Is this plugin supported for rails3 or will it be soon.

nested_form and STI

I'm having trouble using nested_form with STI.
I want to add attachments to discussion as well as posts. I tried several attempts to make it work but always got exceptions.

Do i need to add accepts_nested_attributes_for in discussion.rb ? and has_many :attachments, :dependent => :destroy ?
Do i need to add a type column in the attachments table and make it polymorphic?

class Post < ActiveRecord::Base has_many :attachments, :dependent => :destroy accepts_nested_attributes_for :attachments, :reject_if => lambda { |a| a[:url].blank? }, :allow_destroy => true end

class Discussion < Post acts_as_nested_set end

class Attachment < ActiveRecord::Base belongs_to :post end

Order of create?

When I create a record with nested attributes, the nested attributes tend to be created in a seemingly random manner- I added each nested field in order, and filled them with values from 1-5. However, it gets created in a random order: => 5 3 1 2 4. It's different every time.

So then when I go edit, the form displays the fields in that order as well.. which the user might find confusing.

Is there a way to let it create the records from top to bottom?

multipart form not working with haml

I tried to migrate my edit page from erb to haml, but it gives me error for this line about wrong ) or }:


My config:

nested_form (0.1.0)
rails (3.0.5)
haml (3.0.25)
compass (0.10.6)

JavaScript bug when the parent of a deeply nested attribute is not in a "many" relationship.

The fix proposed in #19 is not complete:

Actually there is still a bug regarding this scenario:

In a Root embeds_one Child embeds_many DeepChild, the name of a deeply nested field would be:

root[child_attributes][deep_child_attributes][0][attribute]

The javascript code responsible to fill the blueprint's parent's ids is broken, since it is always expecting an index after an /[a-z]+attributes/g ex:

root[child_attributes][0][deep_child_attributes][0][attribute]

Mark Up is Escaped

Thanks for all your work Ryan, it is much appreciated.
After implementing nested_form in Rails 3 I have all of the markup being treated as text to be displayed in the browser rather than mark up.
I have followed Ryan's Railscasts and also the Reports/Links example but I still get the same effect.
Snippet from source:

 

New project

<div id="tasks_fields_blueprint" style="display: none"><div class="fields"></div></div> Back

I wonder whether this is to do with the Rails 3 View alteration whereby all output is escaped save for that wrapped in the raw() function?

http://edgeguides.rubyonrails.org/3_0_release_notes.html#other-changes

My Rails skills are not yet sufficient to be able to prove that this is the cause of the problem or, if it is, how to remedy it.

Anyone having a similar issue?

Incompatible with client_side_validations

I'm not sure if I should post it here or at client_side_validations's Issues, but both aren't 100% compatible with each other.

I'm getting various js errors when validations should run.

This is just notifying the problem right now, I'll post more info (and see if I might be able to fix it) as soon as I'm back on that part of this current project.

Undefined method 'nested_form_for'

Hi,

I am using the nested_form_for gem for the first time. I don't know if this is an issue or if I am using it wrong, but I am getting an "undefined method nested_form_for" error.
I have a pretty regular form as you can see:

  <%= nested_form_for @zz_user do |f| %>
        <%= f.fields_for :zz_godfathers do |godfather_form| %>
            <%=  godfather_form.label :user_godson_id %> <br/>
            <%=  godfather_form.text_field :user_godson_id %> <br/>
            <%=  godfather_form.label :description %> <br/>
            <%=  godfather_form.text_field :description %> <br/>
        <% end %>
   <% end %>
 <%= f.link_to_remove "Remove this godfather", :zz_godfathers %>
 <%= f.link_to_add "Add a godfather", :zz_godfathers %>

By the way, I installed the gem and ran the: rails generate nested_form:install command to generate the nested_form.js file that I included in my layout.

Any idea?

Thanks!

_destroy doesn't work

Hi!

Good work Ryan!!! But something goes wrong in my project. I cannot destroy an image (I use carrierwave). If I click on "remove" the _destroy input tag is set to "1" but the image remains on save. Have you an idea? I have added "accepts_nested_attributes_for :assets, :allow_destroy => true" to the asset model and the other code is ok.

I use:

Rails 3.0.3
Ruby 1.9.2

Bye

nested_form doesn't work with haml 3.1.2

After updating haml from 3.1.1 to 3.1.2

link_to_add does not work anymore in the sense, that the hidden blueprint for the nested form fields is not in the source as it should be.

Incorrect new_attribute_ids added to blank forms w/ 2 levels of has_many

I'm developing an app that is very similar to the survey example from your railscast. What I have so far in my models:

class Center < ActiveRecord::Base

has_many :experiments, :order => 'id DESC', :dependent => :destroy

accepts_nested_attributes_for :experiments, :reject_if => :all_blank, :allow_destroy => true

... (more code for thinking sphinx)

//


class Experiment < ActiveRecord::Base

belongs_to :center

has_many :datatypes, :dependent => :destroy

accepts_nested_attributes_for :datatypes, :reject_if => :all_blank, :allow_destroy => true

has_many :personnels, :dependent => :destroy

accepts_nested_attributes_for :personnels, :reject_if => :all_blank, :allow_destroy => true

//


class Personnel < ActiveRecord::Base

belongs_to :experiment

//


class Datatype < ActiveRecord::Base

belongs_to :experiment

The issue I'm seeing is that when I click the link to add a new experiment in my form (the views follow the same practices as the examples you outlined, using fields_for and partials for each model), and then add personnel and datatypes to that new experiment, their child attributes (personnels and datatypes) are added to the first experiment, not the new one. An inspection of the personnels_attributes_blueprint revealed this: center[experiments_attributes][0][personnels_attributes][new_personnels]
Instead of what it SHOULD be:
center[experiments_attributes][new_experiments][personnels_attributes][new_personnels]
Instead of [new_experiments], I get the ID of the existing experiment. Can anyone think of a cause for this? I'm running Rails 3.0.6 on top of Ruby 1.8.7 and using nested_form 0.1.0. Thanks - I'm totally stuck and on a deadline for this week...

ActiveRecord callbacks PROBLEMS

after_create
after_update
after_update
before_save
before_update
before_create

In Model, i want to calculate the collection of price fields. but when the field is deleted it is still in the model.

Thank's

link_to_remove requires arguments

This isn't so much a problem with a code as it is outdated information.

<%= task_form.link_to_remove %>

This fails since it expects an argument, which I found you could pass a string which becomes the content for the link (this makes sense).

Love the plugin.

Add Partial Support

As mentioned in the docs, it should be possible to do this.

<= f.fields_for :tasks %>

And have it automatically look for a task_fields partial and render that for each task.

Support custom form builders

The current implementation (view_helper.rb:4) reverse merges :builder => NestedForm::Builder into the args passed to form_for. This is problematic in a project which has set a custom form builder using ActionView::Base.default_form_builder which appears to be the suggested method for customizing builder behavior. The project's custom form builder will not appear in the nested_form_for arguments and therefore NestedForm::Builder will be used instead leaving the project's custom builders unavailable.

It would be nice if nested_form had better support for custom form builders but I'm not sure what form that should take.
We could remove the reverse_merge and require that projects using nested_form specify NestedForm::Builder or a subclass as their default_form_builder. I think this is closer to the suggested pattern for customizing form_builder but extra work for every nested_form user.
Alternatively we could reopen ActionView::Helpers::FormBuilder and mix in the methods in NestedForm::Builder but those methods shouldn't really be available in every form_for.

What do you think the right approach would be to allow a project to add custom form helpers which should be available within both form_for and nested_form_for?

nested_form_for prototype error?

In my plain rails app I have tested the gem and with prototype there's perhaps a problem that the submit button is dropped out of the form. I can add and remove nested attrivutes, but saving isn't possible.

here is a gist with my form, the models and the rendered html output.

https://gist.github.com/948159

Each field after the call of nested_form_for ist dropped out of the form behind the template blueprint. This could be a prototype js problem.

my system: rails 3.0.7 , ruby 1.8.7 p249

thanks

Graceful degradation without javascript

Would it be possible to support some manner of add remove via the same links for a browser with JavaScript disabled (might already be possible and I'm missing something obvious)?

Extraneous div generated

This should be useful in most cases but I was trying to use this with a ul element. Can an option be provided to toggle this behavior on and off?

Nested_forms doesn't work with content_for

I want to place my image into dynamic sidebar while adding or editing my parent model. The image form shown in sidebar but "link_to_add" and "link_to_remove" helpers doesn't work when I use <% yield :sidebar %> in application layout

I'm not strong in JavaScript, please help me somebody

# recipes/image_fields.html.erb
<% content_for :sidebar do %>
  <%= f.fields_for :photos do |img| %>
   field here
  <% end %>
  <p><%= f.link_to_add image_tag("add_button.png"), :photos %></p>
<% end %>

mistake in regexp in nested_form.js ?

the regex in nested_form.js which is supposed to inject the parent_ids[i] didnt work for me. hence everyhing got attached to the first parent only.

I tested it on railscast #196 + #197 and it put all answers under question 1, even if you created them under other questions.

the version I arrived at is http://gist.github.com/393861

not sure why yours didn't work for me, though.

Duplicate blueprints when using multiple forms

Hi Ryan,

when I'm using multiple forms on the same object (e.g. two instances of nested_form_for(@user)), each of which have nested fields for a different association, the blueprint for the first is inserted after all these forms instead of just the first. It's not a big issue - the forms all work - but it's unnecessary code and it makes the markup invalid due to reused div ids.

I can fix this simply by changing

  @associations ||=| []
  @after_nested_form_callbacks ||= []

to

  @associations = []
  @after_nested_form_callbacks = []

in view_helper.rb, thereby not keeping track of previous associations and callbacks, but I'm sure that's breaking something else.

And yes, I know I could just use one form, but this is for inline editing and I want to send only the bare minimum to the server, so I'm splitting it out into several forms.

Any ideas?

Missing Block

Hello, I get a Missing Block error when I try to use nested_form_for instead of form_for

<% nested_form_for @project, :html => { :multipart => true } do |f| %>

The most wired thing is that it happens when I try to submit something that is not valid and not when I first render the "new" action.

nested:fieldAdded

Is it possible to identify the newly added field from a nested:fieldAdded event?

Form building bug when using partials

I'm using the latest git version of nested_form, rails 3.1 RC4, ruby 1.9.2, simple_form and haml. The problem I have is that it fails to create a new row when using partials in a form. This works:

= simple_nested_form_for @query, :url => perform_query_url(@query) do |f|
  = f.input :string, :label => false

  = f.simple_fields_for :search_attributes do |fi| 
    .filter
      = fi.input :value
      = fi.link_to_remove "Remove filter"

  = f.link_to_add "Add filter", :search_attributes
  = f.submit 'Save'

However, empty divs are created when I move the fields to a partial, like this:

# new.html.haml
= simple_nested_form_for @query, :url => perform_query_url(@query) do |f|
  = render 'fields', :f => f
  = f.submit 'Save'

# _fields.html.haml
= f.input :string, :label => false

= f.simple_fields_for :search_attributes do |fi| 
  .filter
    = fi.input :value
    = fi.link_to_remove "Remove filter"

= f.link_to_add "Add filter", :search_attributes

I noticed that in the last case, the 'link_to_add' link is placed outside of the 'fields' div, while it is inside the fields div in the first case. This is probably the reason why the javascript inserts empty divs. Note that row deletion works fine.

double nested?

Hi,

I have a "Trip" model with return trip and stops like:

Class Trip < ActiveRecord::Base
  belongs_to :return_trip, :class_name=> "Trip", :foreign_key => "return_trip_id"
  has_many :stops

  accepts_nested_attributes_for :return_trip 
  accepts_nested_attributes_for :stops, :allow_destroy => true

In the form I have:

nested_form_for @trip do |f| 
  f.fields_for :stops do |stop_form|
    ...
  end

  f.fields_for :return_trip do |return_from|
    return_form.fields_for :stops do |return_stops_form|
     ....
    end
  end
end

All works fine but the return stops are associated with the original @trip and not with the return_trip.

I don't known if what I'm trying can be done or not.

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.