gpt4 book ai didi

ruby-on-rails - 在 Rails 中有条件地导入 CSV 的语法

转载 作者:数据小太阳 更新时间:2023-10-29 08:43:04 25 4
gpt4 key购买 nike

下面的导入方法需要处理设置为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?,
[...]

启动这个方法的 Controller 在哪里定义

params[:profit_center_column] = @unit.profit_center_column

其中 @unit.profit_center_column = nil

我遇到了意外的 语法错误,意外的 modifier_unless,期待 ')' 在使用 unless 之前我从来没有使用过括号,我希望使用逗号在这里清楚地分隔语句。语法哪里乱了?

正在使用 Rails 4.2.4 和 Ruby 2.3.4。

注意,我也尝试过 if 语句,但这导致加载随机 xxx_column 信息。

最佳答案

您正在将条件传递给 Assets 的构造函数。如果您需要处理它,我建议首先使用确保不为 nil 的值初始化 Asset,然后对其余属性使用 setter:

asset = Asset.new(
unit_id: unit_id,
....

asset.profit_center_id = row[profit_center_column] unless profit_center_column.nil?
asset.save

关于ruby-on-rails - 在 Rails 中有条件地导入 CSV 的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46011697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com