Checkbox list in Ruby on Rails using HABTM

July 3rd, 2008 by Justin Ball

Checkboxes are one of those things that look easy and should be easy, but they aren’t always easy. I needed a solution that could create a checkbox list of languages that a user speaks. So I don’t forget here’s how to do it:

The migrations are important. You have to be sure to exclude the id parameter when you create languages_users or you will get ‘ Mysql::Error: #23000Duplicate entry’ due to the fact that ActiveRecord will try to store a value in the id field that indicates which model created the entry (User.languages << vs Langauges.users). The other option is the create the id parameter so that the direction is maintained but be sure that it is not created as a primary key.

class LanguagesUsers < ActiveRecord::Migration
def self.up
create_table :languages_users, :id => false, :force => true do |t|
t.integer :user_id
t.integer :language_id
t.timestamps
end
end

def self.down
drop_table :languages_users
end
end

class Languages < ActiveRecord::Migration

def self.up
create_table "languages", :force => true do |t|
t.string “name”
t.string “english_name”
t.integer “is_default”, :default => 0
end
end

def self.down
drop_table “languages”
drop_table “users_languages”
end
end

class Users < ActiveRecord::Migration

def self.up
create_table "users", :force => true do |t|
t.string “login”
# other fields excluded for brevity
end
end

def self.down
drop_table “users”
end
end

Here are my models:
user.rb

class User < ActiveRecord::Base
has_and_belongs_to_many :languages
end

language.rb:

class Language < ActiveRecord::Base
has_and_belongs_to_many :users
end

In my user_controller.rb the create and update methods are simple. This is thanks to the fact that you get a language_ids method on the user object because of the HABTM relationship.

def create
@user = User.new(params[:user])
@user.save
end

def update
@user = User.find(current_user)

if @user.update_attributes params[:user]
flash[:notice] = “Settings have been saved.”
redirect_to edit_user_url(@user)
else
flash.now[:error] = @user.errors
setup_form_values
respond_to do |format|
format.html { render :action => :edit}
end
end

end

On to the view:

    <% @languages.each do |language| -%>

  • <%= f.check_box :language_ids, {:checked => user_speaks_language?(language)}, “#{language.id}”, “” -%> <%= "#{language.english_name}" -%>
  • <% end -%>

And we’ll need this helper method:

def user_speaks_language?(language)
if @user && !@user.login.nil? # no sense in testing new users that have no languages
@user.languages.include?(language)
else
false
end
end

The result is that you will get a list of check boxes that update values in the join table that is part of the has_and_belongs_to_many relationship. Rails is very cool

Tags:   · · · ·

No Comments.

Scalr - Scalable Hosting Framework for Amazon Web Services

July 2nd, 2008 by Justin Ball

Amazon’s web services business has sparked a number of business opportunities. Using EC2 and S3 is not especially easy for a beginner, but scalable web architectures aren’t a place for the weak hearted geek.

Enter Scalr. This is an open source project meant to make building a scalable, fault tolerant system on Amazon’s services easier.

If that is still too hard then take a look at scalr.net a service that for $50 a month will manage your scalr instance for you. (You still have to pay all the applicable Amazon charges.

All this comes to us from Intridea which also produces SocialSpring the platform behind Acts as Community.

Tags:   ·

No Comments.

Snakes in the Grass

July 2nd, 2008 by Justin Ball

Last week right before we left for Yellowstone I went out to work on the sprinklers for the garden. I threw on some flip flops because that was easy. While walking around I felt something go over my foot. I thought it was the grass brushing against me ( I don’t like to mow the lawn so it gets long sometimes ). When I looked down I discovered that we have a bit of wildlife living in the garden. A two foot long garter snake slithered off into the neighbor’s yard.

I thought it was gone.

I told my girls about it. Later when they were outside I heard then yelling about a snake. I figured they were making it up. They do that. Right before we left I went out to water the garden. There it was again.

I left it alone. They eat mice and bugs and stuff.

Today my wife almost stepped on it. According to Wikipedia they can have 50 offspring at a time.

Now the snake has to go.

Tags:   · ·

2 Comments

Riding to Work Again

July 2nd, 2008 by Justin Ball

With all the moving around and general craziness at work I haven’t been able to ride to work as much. I finally managed to ride in again. Regardless of whatever else happens today is a good day.

Tags:   ·

No Comments.

Yellowstone 3

June 28th, 2008 by Justin Ball

Day 3. More driving. Always driving. We went to Tower and watched more water fall off rocks. That seems to happen a lot around here. There were a couple of colorful characters hanging around near the parking lot with a sign that said, “save the buffalo” or something like that. The guy was really hairy and looked like grizzly adams. I would think he should have a “save the bears” sign, but I guess they figured the bears with those big claws could take care of themselves. Next to the couple was a sign that said something like “first amendment at work.” Below that was something like the park service has nothing to do with these crazy nuts who haven’t showered in weeks. I’m glad the constitution still works. I told dad that we need to setup a booth. Something like “shoot the damn wolves” or “bison make great burgers.”

We ate lunch at Roosevelt and then hiked to ‘lost falls’ which earns its name, but we found it. The hike required that we walk up a steep trail on loose gravel and yell at the kids to “get back here or I will spank your butt.” When you are young you don’t think about plummeting to your death in the creek below. When you are old you just get mad that you are walking down a stupid trail instead of sitting in front of the gift shop eating ice cream.

The Lamar Valley was next. They say it is the savannah of Yellowstone, except as my brother pointed out you can’t go ripping across the meadows in a Land Rover and then blow through the rivers while chasing down exotic critters. Instead, if you drive more than 45 mph they pull you over, ask for your license and registration and tease your kids (ask Austin about that one). At least they didn’t give him a ticket.

My daughters fascination with animals continued. “I want to see a bear.” Then we saw one. “I want to see a buffalo.” Then we saw a bunch. Sadly they are starting to think that their every wish and desire will be fulfilled at will. We tried to explain that we can’t just make the animals appear on cue, but they keep appearing so we loose. I still haven’t been able to see a bear eat anyone. What a disappointment.

Speaking of crappy experiences, we ate, or rather suffered through a meal at the Roosevelt Lodge. Getting a table took and hour and a half. Getting food took another 30 mins. Eating the food was a mediocre experience. If you are going to eat in the park take your food with you. Most of the staff we dealt with had a lower IQ than the inbred park Buffalo. Xanterra needs to get it together there. For the record the guy behind the gift counter was nice. The guys smoking on the porch were ass holes. Apparently, Wyoming still has lame smoking laws that let you blow cancer dust in everyone’s face. I would have really like to see one of those guys get eaten by a bear:

Bear 1: “Hey Bob, look. Smoked jerk tonight.”
Bear 2: “No way those guys will give you cancer.”

Believe it or not this concludes most of our family trip.

The End

OK, not. A couple of interesting facts about the park:

  1. The only place you can make a cell phone call on your iPhone is at Old Faithful. They take this whole primitive thing way to far.
  2. Edge doesn’t work anywhere so you can’t check your email in Yellowstone. This will force you to focus more on your family whether you like it or not.
  3. 18 miles in Yellowstone is like driving to California. 35mph is way slow. I am pretty sure they are trying to help you recreate traveling the park by horse and carriage.
  4. If you try to drive faster than 35 mph in the park you will most likely plow into a Buffalo and die or plummet 1000 feet and die.
  5. There are bears in this park so if you plan on tent camping then you can think of yourself as a snack in an easy to open package.
  6. Tags:   ·

    1 Comment

Yellowstone 2

June 28th, 2008 by Justin Ball

Sequels are never as good as the original so keep in mind that this one won’t be as good as the last one which wasn’t that great.

I met more rangers today. Two of them seemed like very nice polite people. It probably helped that in the one case the lady was in a brand new air conditioned visitor center. At any rate I now have a sample that I believe shows that only 50% of park rangers are annoying:
4 rangers
2 annoying
2 OK
out of the group one was a good looking blonde so I will also conclude that 25% of rangers are hot blonds.

We went to the Canyon today via the Dunraven pass. It sounds like something out of Lord of the Rings. Actually it is part of the secret ploy to kill as many tourists as possible. This is another one of those roads that remind you of some sort of perilous video game were the bad guys send RVs from Mordor your way to push you off the edge into oblivion.

I guess the view was cool.

The Canyon area of Yellowstone is a great place to reduce family size if you feel like you have to many kids. Artists point is a beautiful final resting place for annoying little Johnny.
“No you go right ahead and climb on those rocks. It’s totally safe.”

Callie had to yell at Jenna to get off the rocks because, well I guess we like her. She did tell her that if she kept doing it she would probably plummet to her death in which case we would have to “throw some dirt, say a little prayer and visit with flowers each year.”

That would be way annoying because who wants to visit EVERY year.

We were going to go back to Tower and from there make our way back to Gardiner, but like I said that road is designed to kill you so instead we drove over to Norris. On the way over we drove the Virginia Cascade loop which is a stupid loop because you drive it and expect to see something then you drive right past the thing you are supposed to see (the cascades) because it isn’t marked and there is no where to stop. There is even a sign that says “your tax dollars at work.” I better be getting those dollars back my next tax refund.

We dropped by Norris geyser basin where sometimes the dirt gets so hot (200) that you could cook an egg - that’s the scientific measure for damn hot. The entire area is filled with boiling water and stinky sulfur like smells. Its like a sauna in a men’s room. There is a geyser there (steamboat) that erupts at sporadic intervals where sporadic might be once in 50 years. We had to get back to the cabin to cook pizza so we didn’t wait. Other than that the ground was filled with little areas of boiling water. For some reason I thought that was one of the most impressive parts of the park - dirt that can boil water. Sometimes I wonder what the hell is wrong with me.

Jenna is still on her wildlife hunt. On the way back there were critters behind every tree so we tuned her out - that is a crucial life skill. They should teach tuning out kids in high school. I guess they do only it is tuning out parents at that point in your life.

Anyway, Jenna says, “I see a bear.” She actually says it “bewa,” but we are expert translators. We tune that out until Jimmy (bro in law) gets on the radio (aren’t we dorks) and says, “there is a bear back there.”

Like any good tourist we whipped around, blocked traffic and took as many pictures as we could. We noticed some really bad tourists way out in the brush CHASING THE BEAR. I really wish we could have gotten a picture of a bear eating a moron, but alas the bear must have been full.

We stopped at the Golden Gate - so named because of lichen - take that San Francisco. This is a creepy road because they couldn’t cut into the mountain so they built the road on pillars out over the canyon. We stopped because we like to take pictures of interesting places to die. They have replaced this thing three times. That tells you it is a bad place to be when one of the big ones hit. It was actually a good think we stopped because it slowed down our journey and ensured that we didn’t slam into the buffalo that decided the bridge would be much easier than a climb over the mountain. For a long time he stood in front of the lot of us like that guy in front of the tanks at Tieneman Square. After a while the critter felt like his political point had been made, but just to be sure he walked alongside the long stream of cars that had been backed up by his protest. I could have reached out the window and pet the thing. That would be yucky.

You would think that our wildlife quota had been met, but right above Mammoth the grouping of cars said otherwise. Right off the road was a young grizzly bear. He didn’t look like he was going to eat any of the stupid tourists who were wandering around so we moved on. You can see non-tourist eating bears in the zoo anytime.

We got back. Ate our pizza and now it is 1 am again.

Tags:   ·

1 Comment

Yellowstone

June 27th, 2008 by Justin Ball

We went to the happiest place on earth, now were off on a family vacation to the stinkiest place on Earth - Yellowstone. Like the Earth’s anus this place belches the nastiest gas you have ever smelled. The girls love it, but hold their noses a lot. I am good with it except for the terrifying narrow roads with the sheer drops seeking to plummet you to your death. There are a lot of animals too. Big ones. I guess that is to be expected. When I was in high school I used to bring dates up here. I got stuck in a herd of 300 buffalo and nearly missed our show at Pierre’s Playhouse. I wonder if that place is still around. My dad doesn’t know, but that was the same day that I had a park ranger pull up while I and said date were picnicking and tell me there they had had reports of a red car a lot like mine flying past obnoxious RVs at 100mph which was very illegal in the park.

I had (and still have) no idea what he was talking about. Luckily my brother destroyed any evidence a few years later by slamming it into a concrete wall.

Park rangers tend to be annoying people that can’t get actual jobs. They tend to think everyone else has absolutely no right to visit their park and for all they care the general populous can just die (which is why they design the roads here they way they do and then put up abstract road signs like “danger ahead”, “just drive off the road and die” or “debris on road” which means there is a boulder up here perched such that if anyone sneezes it will crush you and your atomic family. I made one of those up. My favorite sign is “Rough Break Ahead”. It’s kind of like a fortune cookie from a bad Chinese restaurant. It also describes my life.

I met one of these park rangers this morning. I bet he was from the east coast, works at an investment firm and thinks he can spend the summer in Yellowstone and save the wolves or something. My daughters love maps. I requested 4. One for us so that we can navigate the park and three for the girls. He gives me this “why do you need four maps.” I wanted to say, “we ran out of toilet paper and I need to wipe my ass,” but instead I politely explained that my girls love maps and they learn from them, bla bla. He says, “I’ll give you three.” I wanted to say, “I think you failed math,” but instead I thanked him. Then he gave me a park newsletter and explained that I should review the park rules and regulations with my family and that they can be found on page 2. I grew up a bit more than an hour from the park. This is my backyard. I would have loved to describe to him interesting uses of page 2, but instead I smiled and drove on to the Walmart of Yellowstone, Old Faithful.

Everyone goes there. We must go there too.

Its hard to describe the area anymore. There are more lodges here than hotels on the strip in Las Vegas. The parking lot reminds me of Walmart at Christmas. The company that runs the lodges and restaurants in the park imports employees from around the world. That makes your national park experience ‘multi-cultural.’ In fact it means ‘cheap labor’. The poor guy helping me out had a heck of a time getting hot dogs and macaroni and cheese for my kids. We can barely understand the kids sometimes. Some guy from rural China has no chance.

I think the kids had fun today. Jenna is fascinated by the animals and constantly asks about where they live and can she see them. When she doesn’t see actual animals she looks for signs of animals which are plentiful around the various park features:
“What poop is that?”
“That’s elk poop Jenna”
“What about that poop?”
“That’s buffalo poop Jenna.”
“What about that poop.”
“That’s elk poop Jenna.”
“What about that?”
“That’s where daddy used page 2 …”

Tags:   · ·

1 Comment

51Weeks at ICLS

June 24th, 2008 by Justin Ball

Last year for our open ed conference here at Utah State I built an application called 51weeks to help preserve the presentations and to help people interact. Tomorrow it will be used at ICLS in the Netherlands. The hardest part about these kinds of applications is life cycle management. I am frequently asked to build a ‘quick and dirty’ application. Years of experience has taught me that there is no such thing. Anytime you are asked to build an application you are being asked to commit to keep it alive. What inevitably happens is that someone sees it and assumes that it only needs a few tweaks to adapt it to a new use. If your code is to dirty then forget it. Adaptation almost always runs you into new errors that you have to deal with in new ways.

Whenever creating an application it is always worth the time to get tests in place. It is always worth the time to think about the architecture - not the architecture for the entire system - but rather the big picture. How will the application be deployed? What services will it depend on? What happens when the code becomes obsolete and needs to updated? This is a very real issue with Rails. Methods are deprecated or changed and plugins stop working. I know that most people like to believe that once an application is done it is done. This is a terrible fallacy. Every application requires attention to manage bugs, growth, obsolescence.

Every time I am asked to bring up an old application I am reminded of these issues. Best of luck and enjoy the application to all 51weeks users at ICLS.

Tags:   · ·

3 Comments

Eat and Ride

June 15th, 2008 by Justin Ball

One of my favorite rides is Blacksmith Fork Canyon. If I leave from my house the loop is a little bit more than 40 miles most of which is in the canyon. During the summer it is a little bit cooler than the rest of the valley and the scenery is always beautiful. Now that I am back into riding a bit more I was smart enough to take sufficient food which meant that I didn’t bonk when riding against the wind on the way back.

I remember sitting with my father when I was a kid and watching the Tour de France. It was a bigger deal then and one of the major networks carried it. Now you have to have cable. You can watch golf anytime, but cycling’s biggest event isn’t worth the effort. Golf isn’t even a real sport. Anyway, I was always amazed when the peleton would grab a bite to eat while riding at 20 mph. I tried it a few times and nearly choked. In more recent years as I have started riding more I have found that in order to ride 100 miles you have to learn to eat on the bike. The first time I tried it I choked again. Stupid sport.

In spite of my initial problems I have figured it out and now I usually gnaw on a Cliff bar and down a bottle of Accelerade on the way up so that I am good for the ride down (which always seems to be against the wind). I can now rip open packages with my teeth and eat without choking.

It doesn’t mean I am not clumsy. Yesterday I dropped my Cliff bar on the way up and turned just in time to see it bounce down the road.

I guess I can pick it up the next time I bonk coming down. Yummy.

Tags:   ·

2 Comments

Ruby on Rails - render :action doesn’t run action

June 13th, 2008 by Justin Ball

I want to be cool like everyone else so I use a REST methodology for most of my Rails controllers these days. I wasn’t ever quite sure how my views managed to maintain values for a given object (User, Post, etc) after a failed call to create that that did a render :action => new. Most ‘new’ methods tend to do something like User.new which would create a new empty object. However, my views always had the correct values. For the longest time I have just let this go and not worried about the details, but today I started getting errors on a failed call to create in one of my controllers.

In our ‘new’ method we not only do User.new we also load up a bunch of data into instance variables - @states, @countries, etc. If the call to create fails we call render :action => new. This in does not invoke the ‘new’ method in the controller. Rather it only renders the template (which is how all your values magically stick around even on when the create fails). However, the side effect is that your instance variables - @states, @countries, etc will be nil.

Here’s the Trac Ticket indicating the decision not to run the method.

I would rather they have actually run the method on ‘render :action =>’ and left template rendering to something more like ‘render :template => ‘, but who I am to judge.

Tags:   ·

No Comments.