Rails Seed-Fu Writer why seed got commented out?

蓝咒 提交于 2019-12-07 08:40:31

So, this is a basic string manipulation.

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

Note that you can use .attributes or .as_json, but I read somewhere that .attributes actually takes a lot more time than .as_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. 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.

Hope this helps.

Experiencing exact the same problems, commented output and datetime columns are not quoted. It seems that ActiveSupport::JSON could kill two birds with one stone.

require 'seed-fu'
j = ActiveSupport::JSON
SeedFu::Writer.write("#{Rails.root}/db/dump_seeds/lectures.rb",{ class_name: 'Lecture', constraints: [:id, :name]}) do |writer|
  Lecture.all.order('id').each do |e|
    writer << j.decode(j.encode(e))
  end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!