Rails Seed-Fu Writer 为什么种子被注释掉了? [英] Rails Seed-Fu Writer why seed got commented out?

查看:46
本文介绍了Rails Seed-Fu Writer 为什么种子被注释掉了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,这是我的自定义佣金任务:

So, here's my custom rake task:

task :backup => :environment do |t|
  SeedFu::Writer.write('/path/to/file.rb', class_name: 'Category', constraints: [:id] do |w|
    Category.all.each do |x|
      w << x
    end  
  end
end

并且以下结果文件包含:

And the following result file contains:

# DO NOT MODIFY THIS FILE, it was auto-generated.
#
# Date: 2014-06-15 21:08:13 +0700
# Seeding Category
# Written with the command:
#
#   /home/dave/.rvm/gems/ruby-2.1.2/bin/rake backup
#
Category.seed(:id,
  #<Category id: 1, name: "foo">,
  #<Category id: 2, name: "bar">,
  #<Category id: 3, name: "baz">
)
# End auto-generated file.

问题:为什么种子文件被注释掉了?

谢谢!

推荐答案

所以,这是一个基本的字符串操作.

当我仔细阅读他们的源代码时,seed 方法接受 Hash,而不是对象.所以,我只是将对象转换为它的 Hash 等价物:

When I read closely on their source code, seed method accepts Hash, not object. So, I simply translated the object to its Hash equivalent:

task :backup => :environment do |t|
  SeedFu::Writer.write('/path/to/file.rb', class_name: 'Category', constraints: [:id] do |w|
    Category.all.each do |x|
      w << x.as_json
    end  
  end
end

请注意,您可以使用 .attributes.as_json,但我在某处读到 .attributes 实际上比 .attributes 花费更多的时间代码>.as_json.

Note that you can use .attributes or .as_json, but I read somewhere that .attributes actually takes a lot more time than .as_json.

在那之后,我又遇到了另一个问题:Datetime 列.转换为 JSON 时,日期时间列不会被引用.所以我所做的是:

After that, I encountered yet another problem: Datetime columns. When converted to JSON, Datetime columns are not quoted. So what I did was:

  1. 将列名称(Datetime 类型)存储到数组中.
  2. 将当前对象的 Hash 存储到局部变量中.
  3. 使用.to_s(在局部变量中)将Datetime 值转换为String
  4. 将修改后的局部变量输出到writer对象.
  1. Store the column names (of type Datetime) to an array.
  2. Store current object's Hash to a local variable.
  3. Convert the Datetime values to String, using .to_s (in the local variable)
  4. Output the modified local variable to writer object.

希望这会有所帮助.

这篇关于Rails Seed-Fu Writer 为什么种子被注释掉了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆