rubysherpas / r4ia

A place to file issues for Rails 4 in Action
2 stars 0 forks source link

app broken after editing ticket if it had previously uploaded file(s) #3

Open eriol12 opened 9 years ago

eriol12 commented 9 years ago

The code can be seen on the working branch at: https://github.com/eriol12/ticketee_review.git

If you try to edit a ticket that had file(s) attached when it was created or from a previous edit app will break. Look at the following error! The edit form is setting new rows (equal to the number of files previously uploaded) in the assets table with asset attribute & content_type to [null]! It shouldn't do that! Is duplicating rows with asset & content_type to null! It should be keeping (not replacing) files on nested edits. There ought to be an "if new_record? do this else do that" somewhere in the form view! As well the file number count it ain't right in the edit form when adding more files on top of previously attached files!! Plus when editing the <%= asset.label :asset, "File ##{number += 1}" %> line doesn't work properly!!

action_ reaction_ 1

eriol12 commented 9 years ago

I think this would be a better option. When you update a ticket it ought to list all the previously attached files with the ability to destroy them plus having the option to add more files.

eri

Below is the setup i have for this particular scenario:

    # views/tickets/show.html.erb file
    ...
    <% if @ticket.assets.present? %>
        <h4>Attached Files</h4>
            <div class="assets">
                <% @ticket.assets.each do |asset| %>
                    <%= link_to file_path(asset) do %>
                        <%= File.basename(asset.asset.path.to_s) %>
                    <% end %>
                        <small><%= number_to_human_size(asset.asset.size) %></small>
                 <% end %>
           </div>
      <% end %>

       # files/_form.html.erb file
       <%= fields_for @ticket do |f| %>
           <%= f.fields_for :assets, child_index: number do |asset| %>
               <% if asset.object.new_record? %>
                   <%= asset.file_field :asset %>
               <% end %>
          <% end %>
          <%= f.fields_for :assets do |asset| %>
              <% unless asset.object.new_record? %>
                  <%= File.basename(asset.object.asset.url.to_s) %>
                  <%= asset.check_box :_destroy %>
              <% end %>
           <% end %>
      <% end %>
class TicketsController < ApplicationController
    def ticket_params
        params.require(:ticket).permit(.., assets_attributes: [:id, :_destroy, :ticket_id, :asset, :content_type])
    end
end

class Ticket < ActiveRecord::Base
    ....
    has_many :assets, :dependent => :destroy
    accepts_nested_attributes_for :assets, :allow_destroy => true
end