简体   繁体   English

如何将ActiveRecord Create用于Ruby on Rails的多个记录?

[英]how can I use ActiveRecord Create for multiple records Ruby on Rails?

I have a ruby method that returns multiple records with 7 columns. 我有一个ruby方法,该方法返回具有7列的多个记录。 I want to insert these records to the other table which has more than 15 columns. 我想将这些记录插入到具有超过15列的另一个表中。

How can I use the ActiveRecord Create method in my model to insert those records to match exactly into the new table which has the same column name. 如何在模型中使用ActiveRecord Create方法将那些记录完全匹配到具有相同列名的新表中。

Ex: 例如:

I have a model method like the following: 我有一个类似下面的模型方法:

def self.record_letter_group
  .....
end

In the console, when i try to run this method, it returns the following records 在控制台中,当我尝试运行此方法时,它将返回以下记录

([#<Letter::Group User_ID: "sri", Code: "12345", Group_ID: 15>, 
  #<Letter::Group User_ID: "sri", Code: "12445", Group_ID: 15>,
  #<Letter::Group User_ID: "sri", Code: "12545", Group_ID: 15>,
  #<Letter::Group User_ID: "sri", Code: "12645", Group_ID: 15>,
  #<Letter::Group User_ID: "sri", Code: "12745", Group_ID: 15>,
])

I want to do something like, 我想做类似的事情,

save_records = Letter::Category.create(record_letter_group)

Note: This Letter::Category has 15 columns 注意:这Letter::Category15 columns

Thanks 谢谢

It should look something like this: 它看起来应该像这样:

# whitelist the attributes you want to save to "categories" table
valid_attributes = [ :User_ID, :Code, :Group_ID ]


record_letter_group_attributes = record_letter_group.map { |group| group.attributes.slice(*valid_attributes) }

save_records = Letter::Category.create(record_letter_group_attributes)

暂无
暂无

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

相关问题 如何在Ruby脚本的Rails中使用现有的ActiveRecord模型 - How can I use existing Activerecord model in rails in ruby script Ruby / Rails:如何通过rforce gem通过一次API调用在salesforce中创建多个记录? - Ruby / Rails: how can I create multiple records in salesforce with one API call via the rforce gem? 如何在Rails ActiveRecord中创建,关联和取消关联相关记录与accepts_nested_attributes_for - How can I create, associate, and de-associate related records in Rails ActiveRecord with accepts_nested_attributes_for Ruby on Rails / ActiveRecord:我如何(优雅地)从多个表中检索数据? - Ruby on Rails / ActiveRecord: How Can I (Elegantly) Retrieve Data from Multiple Tables? 如何在Rails外的ruby脚本中使用ActiveRecord? - How to use ActiveRecord in a ruby script outside Rails? 在 Ruby on Rails 中,如何为“以前的记录”创建 has_many 关系? - In Ruby on Rails, how can I create a has_many relation for "previous records"? 在Rails上一次创建多个记录 - Create multiple records at once ruby on rails Rails Activerecord:如何排除具有多个关联记录的记录 - Rails Activerecord: How to exclude records with multiple associated records 在一次调用/查询中创建多个 Rails ActiveRecord 记录 - Create multiple Rails ActiveRecord records in one call/query Ruby on Rails - 为什么我不能使用ActiveRecord :: Base方法? 在哪里使用? - Ruby on Rails - Why can't I use ActiveRecord::Base methods? Where to use?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM