要从csv中导入一个rake任务,通常会这样写
Article.create(
category_id: row[0],
label: row[1],
name: row[2],
integer: row[3],
priority: row[4]
)
但是这些需要被重构,考虑到元结构
Class Import
has_many :importattributes
以下语句语法错误
Article.create(
import.importattributes.each do |importattribute|
m_attr = importattribute.mapped_attribute
sequence = importattribute.position.to_i
m_attr: row[sequence]
end
)
在抱怨syntax error, unexpected ':', expecting 'end'
m_attr: row[sequence]
的行中,如果该行被注释掉,则运行其他操作,因为它们没有事先解析此错误。
我认为这是错误的属性数组的正确创建,因为一个更新操作,在每个属性的基础上
import.importattributes.each do |importattribute|
m_attr = importattribute.mapped_attribute
sequence = importattribute.position.to_i
Article.update(m_attr: row[sequence])
end
不抛出错误。
这不是一个有效的语法m_attr: row[sequence]
。当用作update
的参数时,它被视为散列{ m_attr: row[sequence] }
,可以省略花括号。
Article.create(
import.importattributes.each do |importattribute| # returns `import.importattributes`
# and used as argument for `create`
# nothing from `each` block is used
m_attr = importattribute.mapped_attribute # `m_attr` is unused
sequence = importattribute.position.to_i
m_attr: row[sequence] # invalid syntax
# at the very least it has to be wrapped in {} and used with hashrocket syntax
# to make use of m_attr variable.
# { m_attr => row[sequence] }
end
)
create
接受一个属性的哈希值来创建单个记录,或者接受一个哈希值数组来创建多个记录。导入逻辑的返回值必须是这两个选项之一。为了清晰起见,可以分三个步骤完成:
attributes = {}
import.importattributes.each do |importattribute|
attribute_name = importattribute.mapped_attribute
csv_column = importattribute.position.to_i
attributes[attribute_name] = row[csv_column] }
end
Article.create(attributes)
或一步使用inject
Article.create(
import.importattributes.inject({}) do |attributes, importattribute|
attributes[importattribute.mapped_attribute] = row[importattribute.position.to_i]
attributes
end
)