Console Ninja'ry

In an ever misguided attempt to reorginize this blog, I decided that I had far too many sections. I wanted to use tags more, and sections less. But that left me with the following question – how to move the articles around? Should I do it by hand? Na….

So, the first task to tackle was to make sure that the existing section structure was migrated over to tags.

I cobbled together this little hunk of code

1
2
3
4
5
6
7
8
sections = Sections.find(:all)
for sect in sections
  arts = sect.articles
  for art in arts
    art.tag = sect.name
    art.save
  end
end

This will parse all of the articles in the database, and add a tag for each section that they belong to.

Second was how to move the articles around…

1
2
3
4
5
6
7
8
9
10
11
12
sect = Section.find_by_name("old_section_name")
new_sect = Section.find_by_name("new_section_name")
arts = sect.articles
for art in arts
  if art.sections.include? new_sect
    art.sections.delete sect
  else
    art.sections << new_sect
    art.sections.delete sect
  end
  art.save
end

Since it’s not really an automatable choice, I plugged the correct values in for old_section_name and new_section_name and allowed it to move stuff where I wanted it. Viola, 20 sections down to 4.

Leave a Reply