0

I have a CSV file

Plant_ID,Short_note,Live

YCCXXX1,Description one,TRUE
    
YCCXXX3,Description three,FALSE

an initializer

  require 'csv'    
  plant_table = File.read('app/assets/csv/Plant_table_(USDA_Citrus).csv')
  PlantTable.destroy_all
  csv = CSV.parse(plant_table, :headers => true)
  csv.each do |row|
    PlantTable.create!(row.to_hash)
  end

which render in a view component

<% @plant_tables.each do |plant_table| %>
  <tr>
    <td><%= link_to plant_table.Plant_ID, plant_table %></td>
    <td>PlantX, PlantY</td>
  </tr>
<% end %> 

but I want it to render these ONLY if the LIVE property is TRUE.

I want something like this

#plant_table_initializer.rb
  require 'csv'    
  plant_table = File.read('app/assets/csv/Plant_table_(USDA_Citrus).csv')
  PlantTable.destroy_all
  csv = CSV.parse(plant_table, :headers => true)
  csv.each do |row|
    if csv[row][2] == "TRUE"
    PlantTable.create!(row.to_hash)
    end
  end
cratag
  • 112
  • 12
  • 1
    add next before your if like this: `next if csv[row][2] == "TRUE"` – Greg Mar 16 '21 at 22:45
  • 1
    In your first example, row appears to be a hash. In the second you are calling csv[row][2] which doesn’t quite make sense, you wouldn’t use a hash as the key in another hash, or refer to its content by numbers. Try changing it to this: if row[“Live”] == “TRUE” – AJFaraday Mar 16 '21 at 22:53
  • It worked with both row[2] or row["Live"]. I opted for Live because it's cleaner – cratag Mar 17 '21 at 14:13

2 Answers2

1

Pretty much there just syntax, remove csv part as we are assigning it to row from csv.each do |row|

if row[2] == "TRUE"

not

if csv[row][2] == "TRUE"
Jujhar Singh
  • 129
  • 6
  • I initially thought that, but then I realised that in the first example row looks like a hash. – AJFaraday Mar 16 '21 at 23:05
  • Oh, I'm a ruby noob. When you do: `some_var do |this|` you're hashing some_var = |this|? And making something similar to a for loop? – cratag Mar 17 '21 at 12:36
  • It's a "for each” loop copying the output to the 'this' value. Maybe this would also help https://stackoverflow.com/questions/2846313/finding-out-current-index-in-each-loop-ruby – Jujhar Singh Mar 17 '21 at 21:57
1
if row[2] == 'TRUE'
   render ...
end

Should sort you.

hd1
  • 33,938
  • 5
  • 80
  • 91