【发布时间】:2014-05-23 19:24:01
【问题描述】:
我使用此代码将我的 CSV 文件导入表:
def Hotel.import(file)
allowed_attributes = ["id", "name", "area", "short_name", "zip", "address", "tel", "fax", "staff_name", "information", "created_at", "updated_at"]
CSV.foreach(file.path, headers: true) do |row|
product = find_by_id(row["id"]) || new
product.attributes = row.to_hash.select{ |k,v| allowed_attributes.include? k }
product.save!
end
end
def import
Hotel.import(params[:file])
redirect_to root_url, notice: "Product Imported."
end
但是,此代码仅将 id、created_at 和 updated_at 字段插入到表中。插入命令显示在这里:
INSERT INTO `hotels` (`created_at`, `updated_at`) VALUES ('2014-04-10 07:50:23', '2014-04-10 07:50:23')
我正在使用 rails 4.0 和 ruby 2.0 来完成这个项目。我仔细检查发现错误,但我在这里找不到任何问题,所以请告诉我我错在哪里?
【问题讨论】:
-
我找不到任何错误。
row.to_hash.select{ |k,v| allowed_attributes.include? k }返回什么? -
在您的强参数中是否允许使用 allowed_attributes?
-
@Stefan 原始代码是 '*accessible_atributes' 而不是 row.to_hash.select{ |k,v| allowed_attributes.include? k },但是这个原始代码在rails 4中导致错误,然后我搜索并找到了这个解决方案。这段代码让我很困惑。
-
insert
p row.to_hash.select{ |k,v| allowed_attributes.include? k },Kernel#p检查对象并打印结果,您应该在日志中看到它 -
我发布的行 (
p row.to_hash...) 应该打印一个哈希,类似于{"id" => "1", ...}
标签: ruby csv ruby-on-rails-4