嵌套属性excel导入rails 4

时间:2016-11-04 10:51:06

标签: ruby-on-rails

我的参数喜欢,

params.require(:subject).permit(:id, :org_id, :subject_id, :subject_name, :subject_desc,
                           :subject_color, subject_modules_attributes: [:id, :subject_module_id, :subject_id,
                           :module_number, :module_name, :_destroy,
                           module_details_attributes: [:id, :module_detail_id, :subject_module_id,
                             :module_detail_number, :description, :_destroy]])  

我想通过导入一个excel文件将数据保存在3个表中。如何使用roo gem

def self.import(file)
     allowed_attributes = ["org_id", "subject_name", "subject_desc","subject_color",
                            subject_modules_attributes: ["org_id", "standard_id", "subject_id", "module_number", "module_name"],
                            module_details_attributes: ["subject_module_id", "module_detail_number", "description"]]
    Spreadsheet.client_encoding = 'UTF-8'
    spreadsheet = open_spreadsheet(file)
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      subject = new
      subject.attributes = row.to_hash.slice(*allowed_attributes)
      subject.save!
    end 
end  

我保存了第一个数据表但是在嵌套参数中无法将第二个和第三个表保存为subject_modules和module_details。如何修改我的代码以获得解决方案..

1 个答案:

答案 0 :(得分:0)

我只修改我的代码并为每个表提供create方法,例如

template<typename K, typename V, int CAP>
inline void HashTable<K, V, CAP>::deleteKey(const K & key)
{
    auto& bucket = data[hashCode(key)];
    auto it = std::find_if(bucket.begin(), 
                           bucket.end(), 
                           [&] (auto& item) { return item->key == key; });
    if (it != bucket.end())
    {
        bucket.erase(it);
    }
}

并指定相应字段的电子表格列 感谢。