I am working on a Ruby script that will dump a key, value pair into a yaml file. But for some reason my loop is only grabbing the last instance in the loop. There should be multiple key value pairs.
Code:
# Model for languages Table
class Language < ActiveRecord::Base
end
# Model for elements Table
class Element < ActiveRecord::Base
has_many :element_translations
end
# Model for element_translations Table
class ElementTranslation < ActiveRecord::Base
belongs_to :element
end
# Find ALL languages
lang = Language.all
# Get all elements
elements = Element.where("human_readable IS NOT NULL")
info = ''
elements.each do |el|
开发者_开发百科 lang.each do |l|
et = el.element_translations.where("language_id = ?", l.id)
et.each do |tran|
info = {
el.human_readable.to_s => tran.content.to_s
}
end
File.open(l.code.to_s + ".yml", "w", :encoding => "UTF-8") do |f|
YAML.dump(info, f)
end
end
end
Any ideas?
When you do:
info = {
el.human_readable.to_s => tran.content.to_s
}
did you mean:
info << {
el.human_readable.to_s => tran.content.to_s
}
Otherwise you're just re-assigning info
each time.
If you're going to do this, make info an array: info = []
as opposed to info = ''
.
In this loop
et.each do |tran|
info = {
el.human_readable.to_s => tran.content.to_s
}
end
you repeatedly create new hash with one key el.human_readable.to_s
with different values. However, even if you'll redo it as
info = {}
et.each do |tran|
info[el.human_readable.to_s] = tran.content.to_s
end
you won't get more than 1 result, because key isn't changing - you'll just repeatedly assign it different values. What exactly do you want to get dumped? May be you'd want an array here, not key-value map?
info_array = []
et.each do |tran|
info_array << tran.content.to_s
end
info = { el.human_readable.to_s => info_array }
精彩评论