I have an obj @files which sometimes contain one set of data(one file) and sometimes it contains many files.
I have a create.js.erb and this is what I do at the moment.
<% if @files.new_record? %>
alert("Failed to upload: <%= j @files.errors.full_messages.join(', ').html_safe %>");
<% else %>
$(".container").append('<div id="cfile"><%= j render(@files) %></div>');
<% end %>
Then I have a partial called _file.html.erb
<%= file.name %>
<%= file_.id %>
This all works fine but I'm running into problems trying to create a partial for different types of files.
I want to be able to do something like
if file.first.type == image # (Even If the come in groups they would be the same type so i just need one .type field from one of them.)
$(".different_container").append(render different partial here);
else if file.first.type == doc
$(".another_container").append(render another partial here);
How would I go about this? Please ask if i haven't explained something clearly.
So the problem is that @files can be multiple items or a single item. Before you access it, you can wrap it in Array()
, like this:
file_type = Array(@files).first.type
if file_type == :something
elsif file_type == :something_else
end
What Array()
does is it tries to convert the argument passed to it in to an array. If you pass it a single object, it will return an array with that one object in it. If you pass it an array, it does nothing.
>> Array(1) # => [1]
>> Array(Object.new) # => [Object]
>> Array([1,2,3]) # => [1,2,3]