以下导入方法需要处理设置为nil
的输入变量def self.import(file, unit_id, profit_center_column [...]
CSV.foreach(file.path, :col_sep => "\t", headers: true, skip_blanks: true) do |row|
begin
Asset.create(
unit_id: unit_id,
profit_center_id: row[profit_center_column] unless profit_center_column.nil?,
[...]
启动此方法的控制器定义
params[:profit_center_column] = @unit.profit_center_column
其中@unit.profit_center_column = nil
。
我遇到了一个意外的syntax error, unexpected modifier_unless, expecting ')'
我在使用unless
之前从未使用过括号,我希望在这里使用逗号来清楚地分隔这些语句。语法在哪里弄乱了?
Rails 4.2.4和Ruby 2.3.4正在使用中。
注意,我也试过if语句,但这导致加载随机的xxx_column信息。
答案 0 :(得分:3)
您将条件传递给Asset的构造函数。如果您需要处理它,我建议首先使用确保的非零值初始化Asset
,然后使用setter保留其余属性:
asset = Asset.new(
unit_id: unit_id,
....
asset.profit_center_id = row[profit_center_column] unless profit_center_column.nil?
asset.save