简体   繁体   中英

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.

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. 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. This is most likely because there isn't a column for stock_id on your sample_request model.

In order to solve this you either need to:

1) Remove the stock_id key from the hash. You can use .delete to accomplish this.

2) Or, you can add stock_id to your sample_request model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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