Rails, Ransack, and Associations The Easy Way

Ransack (neé Metasearch) is brilliant at providing ad hoc table searches for users, but  handling all the possible ActiveRecord associations can require workarounds. However, it is bonehead simple to use with a single table. So, we’re going to give it one.

Views are Read-only Tables

A lot of the problems posted on StackOverflow happen when we use associated table fields. An employee has_one section, and we want to filter/sort by the section name. That kind of thing.

I find it’s simpler to avoid the whole issue. I have a demo running at http://search-results-demo.herokuapp.com/ The Employees Search (the landing page) uses results from four different tables, one used twice with an alias, and from another view. It ought to be a nightmare, but it’s actually simple, because it’s using a single virtual table (a Postgresql view.)

There are some other features implemented in the demo, but they’re for future tutorials. You can ignore them, for now.

I wouldn’t use a view for editing, but we only need to show/sort/filter. The view joins any associated tables and makes their columns look and act like native columns in a table.
A view will play nicely with Ransack, because it looks to Rails just like a single table.

How nice it is to get a table with all the columns renamed, all the text concatenation done, all the columns from associated tables sortable and filterable — yum! Null handling is another nice feature: nulls can be shown as “NULL” or “Inactive” or whatever you like, or left as nil values.

Creating/Editing a view in PostGreSQL:

I like to name my views “fil_whatever” (filter), and columns from joined tables as “whatever_disp” if several tables have columns with the same name. For example, if the “sections” and “divisions” tables both have a ‘title’ column, I’d rename them to section_disp and division_disp. I usually include the ‘whatever_id’ columns as well, so that my associations work, although I seldom use them.

That sql will produce a virtual table in PostGreSQL. The view can be used as though it were a table in its own right:

Gives results like:

sql_results

So, we have pulled four tables and another view and an alias into one do-it-all table. However, as far as Rails is concerned, it is just another table, except:

  1. It doesn’t show up in your schema.rb
  2. You need to add a couple of lines to the model to let Rails find the table.

Here’s the controller:

and here’s the view:

There you have it. For my money, that’s a lot easier than fiddling :joins, :includes, scopes, etc. in Rails. YMMV, of course.

Posted in Information, Ruby on Rails, tutorial | Tagged , , , | Leave a comment

Camera Stabilizer? Who knows?

Dsc04134

I had a request a while back: to create a camera stabilizer like this one. The challenge: it needed to be simpler to make.

 

I took that to mean more assembly of stock parts, and less drilling, heating, stretching, etc. I came up with this design, which meets the criteria, and actually shaves a bit off the cost.

It uses a Female Thread – Rod End Bearing ($3.08), a piece of threaded rod ($0.56), a 1′ piece of about anything, and some common nuts, bolts, and washers. It ought to be under $10, easy.

The rod end provides freedom of rotation in roll, pitch, and yaw, and the bar with the stack of washers at the ends provides inertia for stabilization.

I think.

You see, I have never used a Steadicam. I’ve never even seen one used, come to that. I tried it, and my results were distinctly better than hand-held, but what does that mean?

So, to test it, I am looking for someone who knows what’s supposed to happen! If it gets an upcheck, then I’ll feel comfortable publishing the full instructions, price list, and sources.

If you are willing to be a guinea pig, let me know.

Dsc04132_modified
Posted in NewProducts | Leave a comment

Fun Experiment: Same Odds, Different Lucky

There’s a good measure of odds called the “percentile.”

Let’s say you have an Stanford-Binet IQ of 150. What are the odds of that?

According to http://www.iqcomparisonsite.com/IQtable.aspx, that’s the 99.9110907427 percentile. That means that 1 person in 1,125 will have that IQ or higher.

To put it in more graphic terms, that’s as unusual as a man that is 6′ 6″ tall. (You can look it up: go to WolframAlpha, enter the terms “99.91109 percentile height” and set the age to “30 years.”)

Wait a minute! Six-foot-six?

  • If you were 6′ 6″, would you fit in? Literally? Airplane seats, back seats of cars, stadium seats?
  • Could you walk into WalMart and buy clothes that fit?
  • Would you pass unnoticed anywhere in person? You’re shy? Tough!
  • Would people expect different things from you?
  • Would they expect you to somehow fit yourself in?

So, if you have an IQ of 150, you’re just as exceptional as a man that’s 6′ 6″, but it’s invisible! (Unless you also happen to be 6′ 6″, but what are the odds?) The thing that struck me is how differently these “rare birds” are treated.

LeBron James, who is a basketball genius, at least, was identified and set apart when he was 11 years old. By the time he started in the NBA, he’d had 8 years of intensive basketball education. He always had high potential, but without that 8 years of intensive coaching, he couldn’t have achieved such high performance.

LeBron James 2

(Yes, I know he’s 6′ 8″, but the principle is the same.)

Compare a teacher with a 150 IQ kid (IQ) and a coach with a kid that’s going to be 6′ 6″ (TALL):

 (IQ) If the teacher says, “He’s smart, he’ll be fine. I need to concentrate on the kids that can’t pass proficiency,” people might cluck their tongues.

(TALL) If the coach says, “He’s tall, he’ll be fine. I need to concentrate on kids that are going to top out at 5′ 10″,” he’ll be spending more time with his family. Probably the next morning, in fact.

(IQ) If the teacher feels threatened because a kid is smarter than he is, people will call him democratic.

(TALL) If the coach feels threatened because a kid is taller than he is, people will call him to fix their garage doors.

(IQ) If the teacher consistently prefers average work to superior work, he’s working on the kids’ social skills.

(TALL) If the coach consistently plays his average players and benches the tall kid, he’s working on getting his food stamps.

(IQ) “We have a new gifted coordinator. One of the new teachers shows a real talent for working with smaller groups,” i.e., is hopeless in a classroom.

(TALL) “We have a new coach. We hired him away from last year’s city championship-winning school! They’re willing to drop all charges.”

How do they spend their free time?

(IQ) If the 150 IQ kid spends his summers at a computer camp, you’re pushing him.

(TALL) If the 6′ 6″ kid doesn’t spend his summers at basketball camps, you’re holding him back. 

Emotional development?

(IQ) If the 150 IQ kid knows he’s smarter than everyone around him, he has an emotional problem.

(IQ) If the 6′ 6″ kid knows he’s taller than everyone around him, he has a mirror.

Now it’s your turn: who are they talking about here?

(?) “Geek.”

(?) “Standout.”

Access to tools?

(?) “We have a resource room they can use during study hall. I think it has a computer.”

(?) “Outside of gym class? Well, our standouts have use of the gym through the summer, and lighted courts outdoors, and the Booster Club is equipping a weight room, and the coaches have a couple of training camps during the summer. The coaches each make an additional $5000/year.”

(?) “It looks like you can get a $1000/yr from the alumni association, and $500/yr from the Left-handed Plumbers Memorial fund.”

(?) “Full ride at any of three competing state schools. Just don’t get hurt next year when you’re a senior, and the rest will probably make offers, too.”

So, as Wired Magazine puts it:

Bill James, the pioneer of Moneyball-style statistical baseball analysis, points out that modern America is already very good at generating geniuses. The problem is that the geniuses we’ve created are athletes. As James says, this is largely because we treat athletes differently.

  • We encourage them when they’re young, chauffeuring our kids to practice and tournaments.
  • We also have mechanisms for cultivating athletic talent at every step in the process, from Little League to the Majors.
  • Lastly, professional teams are willing to take risks, betting big bucks on draft picks who never pan out.

Because of these successful meta-ideas, even a small city like Topeka, Kansas—roughly the same size as Elizabethan London, James points out—can produce an athletic genius every few years.

And, finally, there’s this from Forbes Magazine:

University of Florida Eliminates Computer Science Department, Increases Athletic Budgets. Hmm.

Go Gators! Go get in line for food stamps!

Sheesh.

Posted in Commentary, Information | Leave a comment

Take the nickel.

Old story: if offered a dime or a nickel, the “village idiot” would always take the nickel. Finally the new guy in town says, “I’ve been watching you. You’re not that dumb, why do you always take the nickel?” And the “idiot” says, “Because if I take the dime, they quit offering.”

Everyone’s heard it. I’m posting it here because virtually all businesspeople and politicians will take the dime, every time. Then they’ll go sit in some sports bar and tell each other stories about how clever they were to get that dime.

The tyranny of the obvious.

Posted in Commentary | 1 Comment

HTML5 Paperclip multiple file upload and attach

Again, we’re trying to make this the most understandable code, without any regard whatsoever for elegance. In the last post we made a do-nothing uploader, just to get some feel for the whole HTML5 file upload process.

This time, we’re actually going to upload, attach, and display files using Paperclip and Rails. Since I am doing this on company time, I’m going to use a new app that I need to get done anyway.

The Summit County Engineer keeps track of Road Records, which are mostly scanned drawings of survey plats for new roads, expanded roads, etc. There’s a bunch of fields about which road, which section, what kind of work, etc. These, you can ignore. The important part is that a Road Record can have a bunch of attached files of varying formats, e.g. tif, pdf, jpg, and doc.

For this tutorial (and my app,) I’m going to call them Appended Assets.

For the most part, it’s typical Paperclip. (one caveat: Paperclip 2.3.14 has a bug — fixed in Paperclip 2.3.15) Most of the non-typical work gets done in the road_records_controller, so let’s look at that first.

It just adds a new AppendedAsset for every file it gets. The fact that the file gets stored in /tmp/ for a bit gives you the chance to rename it, sanitize it, or whatever before it actually gets attached. Don’t forget to add the route:

resources :road_records do
member do
post ‘add_appended_asset’
end
end

The RoadRecord model is simplicity itself.

And the AppendedAsset model is nearly as simple.

Notice that you can do all the usual Paperclip magic, just as you’re used to.

All that’s left is the upload part, which is very similar to what was shown in the last post:

Finally, there is the show.html.erb file, which demonstrates that all the Paperclippy goodness is still there.

It doesn’t look like all that much, but I scrounged all over the web for bits of this. Thanks to all those who post demos and tuts, I guess.

Posted in Information, Ruby on Rails | Tagged , , | 1 Comment

HTML5 multiple file upload (Rails edition)

This is just to gain a little understanding of file uploading in HTML5. To keep it bonehead, I’m going to use plain-vanilla HTML and javascript, and a tiny, tiny controller in Rails. The next post will tell how to use Paperclip to attach the uploaded files.

1. Make a new rails app:

rails new bonehead

2. Rename /public/index.html to /public/old_index.html

3. Stick the following version of index.html in its place:

4. Now, we’ll need a controller:

rails g controller Bounces incoming

5. then fiddle /config/routes.rb

from: get “bounces/incoming/”

to: post “bounces/incoming/”

6. Then edit your bounces_controller.rb so it looks like this:

Now, you have a “looks like it’s working” version of a file uploader to play with. It doesn’t save anything, which is perfect at this point. You can’t hurt anything because it doesn’t do anything. Have a good play with it. Here are some things to notice:

A. When HTML5 file inputs are set to “multiple,” they make a FileList object. Check it out in the console (Firefox with Firebug extension works fine.) There are lots of attributes in there, but these seem to be the most important

B. HTML5 doesn’t provide some of the data we like to get about files in the request, so we send it in custom headers. “X-File-Name” seems to be common practice for the file name, and ‘X-Query-Params’ seems to be common practice for other parameters in JSON-encoded form.

C. I added a couple of attributes to the JSON hash that might come in handy:

a ‘file_model’ attribute so I can say this gets attached to an ‘avatar’ model or an ‘uploads’ model or whatever.
a ‘file_model_id’ so I can say that this file gets attached to some particular instance of the model.

D. The bounces_controller just sends a response — It could be a lot more compliant, but this tells us what’s going on.

Next, I’ll start saving the files using Paperclip.

Tip of the beanie to: http://www.matlus.com/html5-file-upload-with-progress/ and http://blog.new-bamboo.co.uk/2010/7/30/html5-powered-ajax-file-uploads

Posted in Information, Ruby on Rails | Tagged , , , | 3 Comments

Hi-ho, Hi-ho!

Until you start using the machine for actual point-to-point transportation, it’s just a series of shake-downs. In fact, since the trike was designed as a human-powered vehicle, it’s been a series of shake-OFFS. Between the higher average speed and the engine vibration,  every time I rode, something came loose. I’m make a habit of checking all fasteners every so often, and I think I’ve caught them all, now.

So, I rode the eight miles to work and the eight miles home twice this week. Riding with a goal in mind is a much better test of the system. If it breaks, then I’m late for work, or stranded in a bad part of town, or whatever. On the other hand, nothing did break, so now I am really beginning to get some real confidence in the trike as a means of transportation.

I plan my route quite carefully. If at all possible, I use lightly-traveled 4 lane roads — they’re wide enough that people can see me around the bends, and easily pass me in the other lane. Or, second best, residential streets.

I take slightly different routes to and from work. Going uphill, it doesn’t much matter how rough the road; you’re going slowly enough to dodge potholes easily, and the ones you hit don’t rattle that much. On the other hand, going downhill, you want the best possible surface, and you’re going fast enough that you’re moving nearly the speed of traffic. So, I go uphill on residential streets and downhill on 4-lanes, if possible.

One nice part of using residential streets — people just seem to react very positively. Smiles, waves, and thumbs-ups. If I took the Google Street View pictures from the trike, the world would look like a happier place!

Posted in Information, MotoTrike | Tagged , , | 1 Comment