简体   繁体   English

从Excel文件导入数据以在Rails中进行验证和关联以进行建模

[英]Import data from excel file in to model with validations and associations in rails

How to use to import data for model associations 如何使用导入数据进行模型关联

This is my case: 这是我的情况:

class SampleRequest < ActiveRecord::Base
  has_one :sample_request_text_excerpt
  accepts_nested_attributes_for :sample_request_text_excerpt
end

class SampleRequestTextExcerpt < ActiveRecord::Base
  belongs_to :sample_request
end

In the sample_request model, asset type field would be text and image , for text type different excel sheet and for image type different excel sheet , only certain field would be extra in the sample_request_text_excerpt model. 在sample_request模型中,资产类型字段是text和image,对于文本类型不同的excel表格,对于图像类型不同的excel表格,sample_request_text_excerpt模型中只有某些字段是多余的。

For single model no issues , while try to use for associations 对于单个模型没有问题,请尝试用于关联

this line showing error: 此行显示错误:

 sample_request.attributes = row.to_hash

while uploading the text spreadsheet error displayed. 上载显示的文本电子表格错误时显示。

When you are setting the attributes for your sample_request object, you are using a hash. 在设置sample_request对象的属性时,您正在使用哈希。 In that hash there is a key, stock_id and when Rails tries to set that attribute for your sample_request object it can't find it. 在该哈希中,有一个关键字stock_id而当Rails尝试为您的sample_request对象设置该属性时,它将找不到它。 This is most likely because there isn't a column for stock_id on your sample_request model. 这很可能是因为sample_request模型上没有stock_id列。

In order to solve this you either need to: 为了解决这个问题,您要么需要:

1) Remove the stock_id key from the hash. 1)从哈希中删除stock_id键。 You can use .delete to accomplish this. 您可以使用.delete完成此操作。

2) Or, you can add stock_id to your sample_request model. 2)或者,您可以将stock_id添加到sample_request模型中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM