views:

257

answers:

2

If you saw the railscasts on nested forms this is the helper method to create links dynamically. However, after I upgraded to ruby 1.9.2 and rails 3 this doesn't work and I have now idea why.

    def link_to_add_fields(name, f, association)
  new_object = f.object.class.reflect_on_association(association).klass.new
  fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
    render(association.to_s.singularize + "_fields", :f => builder)
  end
  link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
end

here is the javascript

 function add_fields(link, association, content) {
 var new_id = new Date().getTime();
 var regexp = new RegExp("new_" + association, "g")
 $(link).up().insert({
  before: content.replace(regexp, new_id)
 });

}

When I view source this is how the link is getting rendered:

<p><a href="#" onclick="add_fields(this, &quot;dimensions&quot;, &quot;&quot;); return false;">Add Dimension</a></p>

so &quot;&quot; is not the correct information to build a new template and something is going on with how the string for fields is getting set. such as fields= f.fields_for

A: 

If you feel its due to the upgrade to rails ver 3 then do a gem list If you have any older rails versions installed then type this:

RAILS_GEM_VERSION = '(Your older rails version here)' unless defined? RAILS_GEM_VERSION

in the environment.rb file in your config folder. Its also good to freeze your rails version for your app.

Shripad K
The Rails version is managed in the Gemfile in Rails 3. A project also cannot be downgraded from 3 to 2 that easily.
ryanb
+1  A: 

It appears f.fields_for no longer returns the string of rendered fields. I'm guessing this is a side effect from the ERB Blocks change in which case it would only apply to Rails 3 Beta 2. I consider this a bug, and hopefully it will be fixed before the final release, but for now you can do a quick fix like this:

def link_to_add_fields(name, f, association)
  new_object = f.object.class.reflect_on_association(association).klass.new
  fields = fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
    safe_concat(render(association.to_s.singularize + "_fields", :f => builder))
  end
  link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
end
ryanb
Thanks ryanb. and great railscasts!
Sam
I updated the answer to use safe_concat which is probably better here. I also submitted a bug report on this problem: https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/4363-fields_for-not-working-outside-erb
ryanb