views:

441

answers:

1

I am using code found at Railscast 197 to create nested forms using jQuery. The challenge I am facing is that the nested model uses a file_field element, and because of this when looking at the edit view I just see a list of empty file_field elements. Is there a way I can tell rails to display something else (like a disabled text_field) when the user is viewing the edit view, but a file_field when viewing the new view?

This is the partial I am using:

<div class="fields">
    <p>
        <%= f.label :document_type %>
        <%= f.select :document_type, XmlDocument::SOURCES %>
    </p>
    <p>
        <%= f.file_field :inputfile, :class => 'text' %>
        <%= f.hidden_field(:_delete) + link_to('Remove', "javascript:void(0)", :class => "remove_child remove-xmldoc") %>
    </p>
</div>

And this is the jQuery that adds it (modified slightly from the Railscast to add an effect when displaying the partial):

$('form a.add_child').click(function() {
    var assoc   = $(this).attr('data-association');
    var content = $('#' + assoc + '_fields_template').html();
    var regexp  = new RegExp('new_' + assoc, 'g');
    var new_id  = new Date().getTime();

    var newElements = jQuery(content.replace(regexp, new_id)).hide();
    $(this).parent().before(newElements).prev().slideFadeToggle();

    return false;
});

But within my _form partial I have:

<div id="xml_documents">
    <%= label_tag 'XML Documents' %>
    <% form.fields_for :xml_documents do |stream_xml_document_form| %>
    <%= render :partial => "xml_document", :locals => {:f => stream_xml_document_form} %>
    <% end %>

    <p><%= link_to('Add XML Document', "javascript:void(0)", :class => "add_child add-xmldoc", :"data-association" => :xml_documents) %></p>
    <%= new_child_fields_template(form, :xml_documents) %>
</div>

which is what adds the partial, I'm guessing that somewhere in here I need to have a conditional of some sort that tells rails to render a different partial if the object is already created or or not.. Anyone have any ideas as to how I can accomplish this?

+2  A: 

The easiest way to distinguish between 'new' and 'edit' actions is to check for form.object.new_record? This will return true for 'new' action and false for 'edit' action.

So you could do i.e.

<%= f.file_field :inputfile, :class => 'text' if f.object.new_record? %>
szimek
I'm swamped, let me see if I can get this to work, what is 'object', does rails know what this is or are you reference whatever object I am talking about..
Rabbott
If you use form_for helper i.e. "form_for @post do |form|", then you can access the @post object by calling "form.object".
szimek
Sorry it took me so long szimek, but your solution works, thanks for the help!
Rabbott