Reputation: 6244
In my controller i have the following:
@documents = Document.find(:all, :order => "section asc, sub_section asc, position asc, name asc")
@files = Dir.glob("public/downloads/*").sort
In my view i have the following:
<% @documents.each do |d| -%>
<tr class="<%= cycle("","alt") %>">
<td><%= d.name %></td>
<td><%= d.file_name %></td>
<td><%= d.description %></td>
<td>
<%= link_to "Edit", edit_document_path(d) %><br>
<%= link_to "Del", document_path(d), :confirm => "Are you sure boogerhead?", :class => "destroy", :method => :delete %>
</td>
</tr>
<% end -%>
If file_name is not contained in @files then the link on another page that is dependent on that name (file_name) will not work. If there is not a match, I'll color code file_name to indicate there is a problem. How do i check to see if file_name is contained in @files?
Thanks
Upvotes: 0
Views: 133
Reputation: 21564
You can also check if a file exists somewhere in your @directory loop:
File.exist?(file_path)
or if I'm reading your code right, you're checking if a document has a certain file, right? If that is so, why not use paperclip gem so you can add an association that your document should have a file.
Or if that's not possible, you can still transfer that logic into your Document model like so:
def has_file
File.exist?("public/downloads/#{file_name}")
end
then in your loop,
<% @documents.each do |d| -%>
<% if d.has_file %>
<tr class="<%= cycle("","alt") %>">
<td><%= d.name %></td>
<td><%= d.file_name %></td>
<td><%= d.description %></td>
<td>
<%= link_to "Edit", edit_document_path(d) %><br>
<%= link_to "Del", document_path(d), :confirm => "Are you sure boogerhead?", :class => "destroy", :method => :delete %>
</td>
</tr>
<% end %>
<% end -%>
Upvotes: 0
Reputation: 370112
The Array#include?
method checks whether a given item is contained in an array, so you can do:
if @files.include?(d.file_name)
# It is included
else
# It isn't
end
Upvotes: 2