如何在Roo Rails中使用last_row省略空行 [英] How to omit empty rows using last_row in Roo Rails

查看:141
本文介绍了如何在Roo Rails中使用last_row省略空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个members电子表格,其设计如下:

I have a spreadsheet of members designed as below:

我的目标是上传一些列,并排除其他列.在这种情况下,我只希望上传nameageemail,并排除其他.我已经可以使用slice方法实现此目标,如下所示:

My aim is to upload some columns and exclude others. In this case, I wish to upload only the name, age and email and exclude the others. I have been able to achieve this using the slice method as shown below:

def load_imported_members
    spreadsheet = open_spreadsheet
    spreadsheet.default_sheet = 'Worksheet'
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).map do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      member = Member.find_by_id(row["id"]) || Member.new
      member.attributes = row.to_hash.slice("id", "name", "age", "email")
      member
    end
  end

问题是last_row考虑到最后一行(13)的所有行,并且由于表单上存在验证,因此由于空行而导致数据丢失而导致错误(不应这样做)被考虑).有没有办法像我那样只上传特定的列,而又只限制有数据的行?

The problem is that last_row considers all the rows upto the last one (13), and since there are validations on the form, there are errors due to missing data as a result of the empty rows (which shouldn’t be considered). Is there a way I can upload only specific columns as I have done, yet limit to only the rows that have data?

推荐答案

您可能希望将map调用链接到reject过滤器,例如

You might want to chain the map call off of a reject filter like this example

您可能只需要将map行更改为此(假设丢失的行都看起来像上面的行): (2..spreadsheet.last_row).reject{|i| spreadsheet.row(i)[0] }.map do |i|

You may just need to change the map line to this (assuming the missing rows all look like those above): (2..spreadsheet.last_row).reject{|i| spreadsheet.row(i)[0] }.map do |i|

这是假设空白行返回nil,并且空白行将始终使所有四个所需字段都为空白,如图所示. reject调用进行测试以查看id列spreadsheet.row(i)[0]是否为nil,如果是,则从提供给map

This is assuming the blank rows return as nil and that blank rows will always have all four desired fields blank as shown in the image. The reject call tests to see if spreadsheet.row(i)[0], the id column, is nil, if so the item is rejected from the list output given to map

这篇关于如何在Roo Rails中使用last_row省略空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆