All a man needs out of life is a place to sit ‘n’ spit in the fire.

Category: Technology (Page 3 of 4)

Tech tips, howto’s and other writings mostly concerning with Linux and Open Source or Free Libre Open Source Software (FLOSS)

Ruby on Rails – Insert Multiple Child Records

Yes, I understand this is going to be a weird post for some of you.  Frankly, I haven’t been writing enough about what I spend most of my day doing, so here it is.

­I have been having a bafflingly hard time trying to figure out the proper way to insert multiple child records from one single webform.  It is the standard fare for posting things like invoice headers and details.  Say for example, you’ve got an invoice record which consists of an order number, date and whatnot.  That particular piece of tabular data is then considered the parent of its child line items (product_id, description, quantity, price, etc).  So you’ve got this Order which consists of an invoice and line items. 

It’s pretty basic, but I’ve had the hardest time figuring out how to do this is Ruby on Rails.  I know it’s not hard in theory, but with Rails, since there is only One Right Way(TM) to do things, ’cause you’re on Rails, it takes a bit of doing to figure out this Right Way(TM).  I personally don’t have a problem doing it Rails’ way, but please dear God, just tell me what it is.  I bought the book and everything.

So here’s the dope, folks.  Please correct me if there’s a better way of doing this, ’cause I’m a Rails n00b.  For reference sake, I am using Ruby on Rails 1.0 with Postgres 8.0.4 and Ruby 1.8.4

First the webform:

<ul id=items>
   <% for item in @items %>
   <li><%= check_box_tag 'line_item', item.id, checked=false, {:name => "line_item[item_id][]", :id => "line_item_id_#{item.id}" }  %><label for="line_item_id_<%= item.id %>"> <%= item.title  %></label></li>
   <% end %>
</ul>

Make sure to use check_box_tag instead of check_box.  check_box holds a hidden text input that by default inserts a 0 into the database.  From http://rubyonrails.org/api/classes/ActionView/Helpers/FormHelper.html

The checked_value defaults to 1 while the
default unchecked_value is set to 0 which is convenient for
boolean values. Usually unchecked checkboxes don’t post anything. We
work around this problem by adding a hidden value with the same name as the
checkbox.

You don’t want that.  You want the plain vanilla check_box_tag which does none of that nonsense, because you in fact, don’t want your line_item table being filled with up with all kinds of line_items referring to product "0" or product "NULL".

So that’s our form.  The line <% for item in @items %> comes from the items.rb model and is just a little database query to get all the items associated with a particular order for posting in our invoice.  Why would we use checkboxes?  Well, maybe we’re not going to invoice the whole order.  Maybe we’re out of some items.  We’ll let our warehouse guy check off the checkboxes on his wireless pda.  How’s that?

If you were watching closely, you’ll notice that I modified the check_box_tag behavior with options of my own with the following:

:name => "line_item[item_id][]"

This is what gives us multiple lines (an array of items) to pass to the controller.  [] is the important part.

Now, so far this is easy, or at least I thought so.  I’ve done this a hundred times in php, but that’s just the problem, I got tired of writing and re-writing this.  I wanted Rails to handle all the parent child relationships for me and leave me alone.  I’m lazy.

But I couldn’t figure out exactly how to do this.  Frankly, I’m still trying to fit all the method/class/object/instance/variable blah blah blah into my head and keep all the Invoice invoice invoices straight.  I know, I know, it’s probably me, but I’ll wager there are a few more slow-witted programmers out there for whom this is all so confusing.  A phrase that I have been becoming more familiar with while working in Ruby on Rails is, "Use the force."  It’s funny, but most of the time when I relax and make stuff up without trying to "understand,"  things usually Just Work(TM).  Jedi Programming… who knew?

So we’ve got our form.  Now we need to post the parent and the children in one fell swoop.

Now for the model (no, not Victoria’s Secret):  Invoice will not reference the children (the children will come running when they hear their parent’s voice regardless of whether they are called by name).  The parent "has_many" children and does not bother remembering their names or ids or anything.  The children on the other hand "belong_to " (or reference) the parent and are tattooed with the parent_id stamp of ownership (big ears for example).   When they are required, they will all line up under the parent and file out like good little children.

Got it?  Parent -> has_many :children, Child -> belongs_to :parent – the model of a perfect Catholic Rails family.

Now we need to post the stuff.  This is a snippet from the invoice_controller.rb:

   def create
      @invoice = Invoice.new(params[:invoice])
      @invoice.order_id = @session["order_id"]
      for item_id in params[:invoice_item][:item_id] do
              @invoice.invoice_items << InvoiceItem.new(:item_id => item_id)
      end
      if @invoice.save
         flash[:notice] = 'Invoice was successfully created.'
         redirect_to :action => 'list'
      else
         render :action => 'new'
      end
   end

order_id is stored in the session array and is used to reference the invoice.  The invoice in turn has items added to it for each item_id in the params passed from our form.  What happens on @invoice.save is the following:

  1. Rails inserts the invoice header (the parent)
  2. Immediately fetches currval(invoices_id_seq) to retrieve the newly created invoice_id
  3. Uses that invoice_id number and iterates over the invoice_items inserting both the item_id and invoice_id
  4. commits the results if successful

That’s it!  Easy, huh?  Well it took me all day to figure it out.  I knew it was easy, but perhaps I don’t have mad google sklz or something, because it left me scratching my head.  Hopefully someone will find this useful.  Leave a comment and I’ll do my best to answer your questions.  If not, I’m sure I’ll forget it in a few months and have to reread this *G*.

Gil The Jenius: Education For Us

The other day, Gil Schmidt, summed up something I think I’ve trying to say for the past few years. I say "trying" because I’ve been clubbing the damned thing for so long, I don’t even know what it looks like any more. Gil’s come along and said to me, "You know that thing you’ve been bashing, that you forgot what it was? Well – it’s this." And he laid it bare to me again. I now know what my prey looks like, and my hunger induced insanity melts away to reveal new resolve.

Gil The Jenius: Education For Us

The global economy of this century is not a preserver of status quos; in truth, it destroys them with chaotic speed. A nation educated to bow to stasis, to "follow the lunkhead" misery is not now nor ever will be a true global economic player. But a nation is not an entity: it is a collection of individuals united by common characteristics and sharing, often unconsciously, common vision and goals. To develop the nation, develop the individual. To develop the individual…well, that’s Our job.

It’s funny, but I never knew how the masses could be inspired to revolt in Latin America. What could someone write or speak that would bring new focused clarity to their plight? I just didn’t see it. Maybe now I’m starting to get an inkling.

Wifi Drivers for Linux PPC

Let me get geeky for a bit.  I recently decided that I was not going to be the last person on earth without wireless access, so I marched off to CompUSA to buy a wifi card for my G3 Powerbook (Pismo).  I know, I know, I should have checked the hardware compatibility lists, but ever impatient, I thought, how bad could it be?  I’ll buy two and if one doesn’t work, I’ll stick in the other. 

Neither worked.

Bah!  Curse my passionate self.  I erred in the predictable fashion.  I fell victim to the classic blunder, the most famous of which is never get involved in a land war in Asia, but only slightly less known is this: with Linux you must research.  With Linux on the PowerPC, you must research and pray.

So, first of all, the Broadcom family of chips (Apple’s Airport, Motorola, and a bunch of others will not work with Linux on PPC).  With Linux on Intel, you’re okay, because you have ndiswrapper with which to run your Windows drivers in Linux.  However, with PPC you will have no such luck, as ndiswrapper is strictly an Intel x86 endeavor.  No, with PPC your best bet (as I later found out) is to buy one of the D-Link family of products.  From what I can tell, they have native support across the board in Linux (my own card, a DWL-G630 – 802.11g, works flawlessly). 

To get it working, you first have to install the drivers from the madwifi project (your distro should have it available for installation), make sure you have PCMCIA drivers installed, and you’re now spilling coffee on your keyboard at one of the many nationwide Starbucks locations. 

The biggest challenge was figuring out which brand of wifi card supports Linux natively – because NONE of them say so.  They all say "Windows 9x, 2000, XP, and 2003."

After two trips to CompUSA, I now have a D-Link card and my working laptop.   Remote X works, and I get about 1 megabyte/sec transfer rate through the concrete walls of my home.  

And now you know the rest of the story.  D-Link, D-Link, D-Link!

The Life of a Sys-admin

It’s a mixture of the irritating, the banal, and the absurd.  Welcome to my life.  Take a peek.

 (08/25/2005 10:01:33 AM) Laura:
well you did not correct me… my bad — I should have insisted on your attention you have been so busy.. . SO SORRY!!!

Luciano did say he was kind of lost in the menus but I thought they are so easy he could not have done harm.
    
Is that where all the emails are misdirected

(08/25/2005 10:01:42 AM) james:
so that was the problem… all fixed now, their mail should be arriving

(08/25/2005 10:01:59 AM) Laura:
thanks

(08/25/2005 10:04:55 AM) james:
I need fracking coffee

(08/25/2005 10:05:14 AM) Laura:
yes…

(08/25/2005 10:07:38 AM) Laura:
they say they are still not getting any mail…

(08/25/2005 10:09:25 AM) james:
hey
look, all you impatient and stupid people (that includes you too) there
is 150 megabytes of email that needs to beat back the buffeting
onslaught of the outgoing storm named eventos… the little email must
plant itself firmly, bracing against the bits as they fly past, to
struggle perchance to dream, of someday arriving at their intended
destination, safe at last – happy to be home.
    
for frack’s sake

(08/25/2005 10:10:16 AM) Laura:
what a nice story!  So colorful and wonderful a nice change in this dreadful world of bits and bytes

IT Employee Attitude Adjustment

You’ve probably noticed it.  I’ve noticed it.  IT personnel have gotten less responsive over the last few years.  They complain more, are harder to deal with, and less motivated than I’ve ever seen.  The cliche of the BOFH (Bastard Operator From Hell) was one thing.  Today it’s totally different.  IT people don’t love their jobs anymore.  Whereas the BOFH of yesteryear truly loved the torment he inflicted on his L-users, today’s LOFH (Lazy Operator From Hell) just doesn’t care.  He really doesn’t.  He doesn’t care if you’re mad, if you yell, if you call him names, tell his boss he sucks, rant and rave up and down the halls. He just doesn’t care.

He’s not paid enough to care.

And that’s the difference.  Whereas before in the land of mainframes and business automation, highly skilled technical people were paid large fees to make stuff run well.  And for the most part it did.  Because of the power these high priests of the arcane wielded, they tended to be bastards, condescending.  But it was all part of the mystic and mostly everyone was happy.

Enter desktop computing.

Today’s sys-admin is more than likely the user that sits in front of the computer using email, word processing, spreadsheets, etc.  You, the end user, are your own admin.  Professional sys-admin’s are more than likely just help desk support, and worse than that, relegated to company overhead, while employees with the desktop computers are the bread and butter.

“Make it work, you worm,” you can hear them mutter under their breath whenever there is downtime.

IT guys don’t get paid well, and as a result, they take their compensation in other ways, surfing the net, running side consulting jobs from their employer’s business, screwing around, taking long lunches, being unresponsive, rude, surly.

I’ve seen it all, I work with these people every day, and it’s always the same.  They’re bored, under appreciated, underpaid, and unhappy. Transition smoothly with outplacement support for employers.

“You wanted to be your own sys-admin?  Now that you’ve got that fancy schmancy WinXP on your desktop so easy to use, so powerful.  You think you don’t need us?  You think this stuff is simple?  Do it your god-damned self.”

Desktop computing has gotten so cheap that we labor under the false illusion that business automation is cheap, a commodity, that Information Technology is one step above the toilet paper stocking service.

Even in conversations about modern business infrastructure, it helps to remember that safety services still play an important role. Reliable Fire Watch Guards in Minneapolis help businesses stay protected during system outages or emergencies while operations continue.

Next time you have that bean burrito, and you get that after lunch peristaltic action and there’s no TP… bet you wish you had some TP now doncha?

OS Agnosticism

I’ve come to the conclusion that the Operating System is irrelevant, that the base that allows a computer to be useful no longer can or will be a primary focus.  I arrived at this conclusion after having Laura’s computer completely die.  Lately, she’s been using her old Windows 98 machine while I figure out what I’m going to do.  

Yesterday I set up X windows for her under Cygwin on Windows 98 so she would have access to her Linux desktop on the terminal server. 

X -query 192.168.1.3

and voilá there’s her desktop as if she’d never left it.  I thought it was cool, but I started wondering, why would she need that?  She’s got her OpenOffice under Windows 98, she’s got her jabber instant messenger client.  She uses Firefox which doesn’t care what it runs on.  She doesn’t use Gimp very often, but it’s there too.  I can even install Inkscape if she should desire it.  In short, I can’t think of, and neither can she, a single reason to use her Linux desktop.  All the infrastructure stuff runs on the Linux server: the webserver, database server, filesharing server, access controls, filters, and whatnot.  The email is accessed via IMAP so you can use webmail, or Outlook, or Thunderbird, or Outlook Express, or Evolution, or Kmail.  Anything you can dream up and it’s all synchronized.  It all works seamlessly with Windows or Linux or Macintosh.  All her documents and images are completely divorced from whatever lies beneath, normally ready to strike and swallow up your precious data.  Call it a reinforced hull so you don’t end up being fish food.

For myself, I am happy with my Linux environment.  I do not like Windows XP or any of its ilk.  It’s a personal choice, not an indictment on which is inherently better.  You may like XP.  I may like Linux.  Both seem to run Free Software just fine, and make the issue mostly about personal taste or comfort.  For example, I like the way my apps behave in Linux.  I like my kpovmodeler front-end to Povray.  I like Quanta for some webwork.  I like vim for programming and webwork.  I like GIMP for graphics work.  I like xmms as my music player.  I use K3B as my dvd/cd burner (I love it).  I use Scribus for desktop publishing.  But I guess for me the ONLY killer app is the bash shell… which once again is available as part of Cygwin, so I guess it’s a non-issue.

You see?  It doesn’t matter anymore and I like it that way.

The New Vietnam

Sometimes I long for a bit of drama in my
life, something with which to struggle, a worm, a trojan, or a virus or
two. Linux is boring, and I am feeling a bit of guilt for my Microsoft
brothers fighting Charlie in the jungles of the third world, while I
cool my heals in Canada. I feel this guilt purchasing with impunity
online, surfing freely, accessing remotely.  Will my conscience ever be
free and clear again?

I do feel I should do more for our
boys. I should do my duty and get infected by spyware or something, do
it for honor, do it for my country.

Show your patriotism and get infected by spyware today! Use Microsoft software!

The Monks of our Generation, los melancólicos

They have always existed, severe melancholics, those for whom
perfection is an attainable goal. The monks lock themselves away with
their craft to the exclusion of what we would call normal. Are these
noble endeavors, to cloister oneself far away from the distractions
of human life? They chose a lifetime of solitude, silence, rigorous
study, self denial, not for ignorant religious reasons, but for the
sake of their craft. These were the ones who preserved history,
recorded deeds, transcribed knowledge and kept it safe
for posterity. They wrote great works of philosophy, theology, and
science. They were the maladjusted geeks of their generation, so they
hid themselves away from the frat boys.

Still, I can’t help but feel a sort of pity for those so ill
equipped to deal with the stupidity and chaos of human existence that
they must flee from it. I cannot help but feel like they’ve missed
out on something, they who lock themselves away from humanity in
search of order, perfections, the divine.

I get the same feeling reading Slashdot,
and I’ve come to realize that programmers are our modern monks, quasi
agoraphobic masters of their craft, who wish strike out all discord
in the universe, make it perfect.

More specifically, these Slashdotters generally cannot tolerate
children, are set on never having any and express disdain for those
ignorant souls in the majority, the stupid politicians, the idiot
masses, the uneducated fools that hurt the environment, muck up the
order, impinge on our monks’ solitude. The disdain is expressed in a
variety of manners, from a quick sharp word to the author of a
factually incorrect statement, to the merciless flagellation of
abusers of grammar or spelling. Slashdotters revile rules imposed
upon themselves, limitations that rob from them the tools used to create
order. Witness the rebellion in both Europe and
the US over software patents. Programmers regard source code as
speech, and to patent it, to limit it, is tantamount to a civil
rights violation. Slashdotters hate spammers as well, these idiot
purveyors of Viagra, cheap real estate, and get rich schemes
withhold from our programmers free and open communication with their
fellows. It is as if all across the silent monastery rang the din of
Brittney Spears 24/7.

Happiness is irrelevant. There is only truth. There is only
perfection, and to the monk, perfection is attainable, if only he
could concentrate on it a bit harder, for a bit longer, with the
right tools, away… from… it… all.

I have come to realize that my pity is misplaced, for the monks of
our generation, as in generations past, are who they are and are
compelled to embark upon their quest to attain the unattainable. They
are the dreamers, the philosophers, the unreasonable forces in the
universe that create, if not perfection, at least a detailed map of
what it might look like. And that is a start, for without a map, how
may we know where to go, what to do with ourselves?

Data Migration Day Three

When will I learn? I don’t care how many times in the last five years I’ve had to mess with LDAP, I never learn. Why the hell don’t I write shit down when I figure it out. Do I enjoy re-learning the same stupid crap over and over and over? Must be.

Okay here’s the thing. I shall endeavor to remember the following:

  1. When upgrading an LDAP directory service, make sure to dump the data out of the running system before breaking it down.
  2. If I fail to do #1, please oh please dear God have made a backup of it at least. chroot into the old environment, launch the ldap server, slapcat the whole shebang and proceed to step three
  3. slapadd the slapcat-ed ldif file… NOT ldapadd. ldapadd is suggested in most places as the tool of choice, but slapadd is what I need. Geez, stupid fuckers.  Of course who’s the bigger idiot, the fool or the fool who follows him?
  4. Make sure to modify the slapd.conf file to change the default db from ldbm to bdm.

Pretty damn simple, eh? Not so simple when I’ve forgotten more of this LDAP shit than any sane person would care to remember.

While I’m at it, please oh please, remember for the next time about the dbmmange httpd password files. You’ve got to export the old entries, and then import them dbmmanage2 users import < old-data, modify the .htaccess files and be done with it.

Oh and a neat trick for dumping reliably an entire PosgreSQL database for an upgrade:

pg_dumpall > backup.sql

stop PostgreSQL, upgrade it, wipe the data directory, run initdb as user postgres and then psql -f backup.sql template1

Flawless. At least that part went well. The cursing was fun though.

The Sweet Nuanced Tones of Fuck

I installed all fresh shiny brand
new super gooey-licisous software on this server today. The new OS and
tools weren’t the hard part, it’s the migration of all
the old data, the interesting easter-egg hunt of new features
masquerading as error messages, and the cursing. Ahhh, it wouldn’t be a
software upgrade without the cursing… sigh, I’ll look back fondly on
this one day and remember the cursing, for it was rich indeed.

"Son, in my day, we knew what voice activation was."

It
was the subtle nuanced language that only system admins knew how to
speak… that and the sound of the keyboard being impact-hammered into
oblivion. Pure poetry…

*sniff* brings a tear to my eye. I need a pint, I’m feeling in a bit o’ a brood.

« Older posts Newer posts »

© 2026 El Gringoqueño

Theme by Anders NorenUp ↑