如何在Roo Rails中使用last_row省略空行 [英] How to omit empty rows using last_row in Roo Rails
问题描述
我有一个members
电子表格,其设计如下:
I have a spreadsheet of members
designed as below:
我的目标是上传一些列,并排除其他列.在这种情况下,我只希望上传name
,age
和email
,并排除其他.我已经可以使用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?
推荐答案
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屋!