开发者

Rails nested form using file_field element

开发者 https://www.devze.com 2022-12-19 23:20 出处:网络
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 v

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 a开发者_如何转开发ccomplish this?


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? %>
0

精彩评论

暂无评论...
验证码 换一张
取 消