neanderslob
neanderslob

Reputation: 2693

Comparing file names in driectory with database

I'm currently looping through files in a directory to see if any file names from a particular directory match listed file names in a database. I am doing this as follows:

Dir.foreach("#{path}/#{directory}") do |file|
            puts "File name is #{file}"
            puts "true if in database: #{@company.assets.where(uploaded_file_file_name: file).exists?}"
end

The issue is that when I added all the file names to the database for a sanity check, exists? kept coming up false.

However, if I store any of the names as a variable and check exists?, it comes up true. I just can't get it to work off of |file| in the loop above. I should note that puts #{file} simply displays the file name, leading me to believe that file is just a simple string. Is there something special about Dir that would cause this? Many thanks in advance.

Upvotes: 0

Views: 77

Answers (2)

neanderslob
neanderslob

Reputation: 2693

Figured out the issue. Paperclip was replacing any whitespace with underscores, so most of the entries had one or two underscores which I'd overlooked. I just had to do the same to file in the loop:

filesnake=file.tr(" ", "_").tr(",", "_")

And then compare filesnake instead of file

@company.assets.exists?(uploaded_file_file_name: filesnake)

Upvotes: 0

spickermann
spickermann

Reputation: 106932

Dir.foreach iterates over filename including the path. I guess you just stored the filename (without the path) into your database.

Please try:

@company.assets.exists?(
  uploaded_file_file_name: File.basename(file)
)

Upvotes: 1

Related Questions