在 Rails 3 中使用 ActiveRecord 插入非模型数据的最佳方法?
我正在 Rails 3 项目中导入数据。我有两个略有不同的场景。我想知道是否有更好的方法。
场景#1
- 我使用 DBI:ODBC 执行动态生成的 SQL。 (DBI,因为 ActiveRecord 不支持此数据库。)
- 我循环遍历结果集,并使用 ActiveRecord 将数据插入到非模型表中。
插入语句是使用 Ruby 字符串格式生成的,如下所示:
while row = result.fetch do
values = row.to_a
insert_sql = "insert into table (column1, column2) values (%s, %s)" % values
ActiveRecord::Base.connection.execute insert_sql
end
是否有更好的方法来执行此操作?我不太热衷于使用格式化字符串。
场景#2
场景#2 与#1 类似...它不是从DBI 获取数据,而是来自CSV 文件。所以在这种情况下数据是文本(或字符串)。再次,我使用带有 %s 说明符的 insert 语句,并使用 ActiveRecord 插入到非模型表中。
有更好的办法吗?
I'm importing data in a Rails 3 project. I have 2 slightly different scenarios. I'd like to know if there is a better way.
Scenario # 1
- I execute dynamically generated SQL using DBI:ODBC. (DBI since ActiveRecord does not support this database.)
- I loop through the result set, and insert data into a non-model table using ActiveRecord.
The insert statement is generating using Ruby string formatting like such:
while row = result.fetch do
values = row.to_a
insert_sql = "insert into table (column1, column2) values (%s, %s)" % values
ActiveRecord::Base.connection.execute insert_sql
end
Is there a better way to do this? I'm not too keen on using formatted strings.
Scenario # 2
Scenario # 2 is similar to # 1... Instead of getting data from DBI, it's coming from a CSV file. So in this case the data is text (or strings). Again, I'm using the insert statement with %s specifiers in it, and inserting into a non-model table using ActiveRecord.
Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这要看情况。如果您有很多行要插入并且不需要 ActiveRecord 的验证,那么您的方法似乎是正确的。但是,如果一次插入多个记录,则工作速度会快得多,如下所示:
如果您更喜欢通过验证,则需要将数据源的每一行转换为 ActiveRecord 对象。虽然提供验证和回调,但这种方法要慢得多。
That depends. If you have a lot of rows to insert and you do not need validation from ActiveRecord, your approach seems right. However, it would work considerably faster if you inserted more than a single record at a time, like this:
If you prefer passing validations, you would need to translate each line of your data sources into an ActiveRecord object. While providing validations and callbacks, this approach is MUCH slower.