using text_field_with_auto_complete and form_authenticity_token 0

Posted by matthewcarriere

Rails 2.0 introduced protection for Cross-site request forgery (CSRF). This is turned on by default in your Rails applications. However, many developers are turning off this valuable protection rather than making the changes necessary to use it. This seems the same to me as leaving your door unlocked while your friend visits because cutting keys is hard. Case in point: text_field_with_auto_complete

You know you have run into the new CSRF protection when you see this error in your Rails application:

ActionController::InvalidAuthenticityToken

This is the point where you Google the error and receive one of the following pieces of advice:

1. Turn off RequestForgeryProtection all together.

Translation: “Thanks core team, but I am not interested.”

# add the following line to your application.rb or one of your environment.rb files. # why not production? (sarcasm) config.action_controller.allow_forgery_protection = false

2. Turn off RequestForgeryProtection for just one controller.

Translation: “This controller doesn’t really need it anyway.”

skip_before_filter :verify_authenticity_token

3. Turn off RequestForgeryProtection for just one action.

Translation: “No one will notice.”

protect_from_forgery :except => :attack_me

So let’s see how easy it is to utilize this new feature!

I was working with the text_field_with_auto_complete in a pretty basic form:

<%= text_field_with_auto_complete :model_name, :attribute_name, { :size => 10 }, { :skip_style => true} %>

For those of you who aren’t familiar with this there is a nice post on the Rails Wiki

When I tried to perform my auto complete I received the ActionController::InvalidAuthenticityToken error.

Why? Because basically my Ajax request did not include a security token that RequestForgeryProtection uses to validate my request is coming from the right place. All you need to do is add this token to the parameters sent with your request. Rails makes this easy with the helper: form_authenticity_token. The token name RequestForgeryProtection will be looking for is: authenticity_token.

So let’s add this to our text_field_with_auto_complete:

<%= text_field_with_auto_complete :model_name, :attribute_name, { :size => 10 }, { :skip_style => true, :with => "'model[attribute]='+ $('model_attribute').value+ '&authenticity_token='+ '#{form_authenticity_token}'" } %>

Now when I performed my auto complete it worked flawlessly! Now to refactor that string… any suggestions?

Update August 25, 2008

Learned two things working with this…

  1. It’s automatically doing a POST, so by changing the method to GET I can avoid having to deal with the authenticity_token.

<%= text_field_with_auto_complete :model_name, :attribute_name, { :size => 10 }, { :skip_style => true, :method => :get, :with => "'model[attribute]='+ $('model_attribute').value" } %>

  1. And with that out of the way I don’t need to specify the parameters since by default it will send back the value of the text field.

<%= text_field_with_auto_complete :model_name, :attribute_name, { :size => 10 }, { :skip_style => true, :method => :get } %>

That’s a lot cleaner!

Learning Ruby on Rails with Heroku Episode 1

Posted by matthewcarriere

Ever since I saw Heroku I wanted to use it for a screencast on learning Ruby on Rails. This weekend I finished the very first episode! This episode is fairly light on Ruby on Rails content because I was so focused on screencasting and learning all about video and audio production for the web.

So take a look and tell me what you think. I used Vimeo for hosting the video. I also produced the video in HD… however I didn’t realize that Vimeo only streams the HD content on their site, not the embedded video. So to view the best possible video you should view it on Vimeo. here is the link. You can make it full screen and enjoy the HD in all its glory.

Please feel free to leave some constructive criticism regarding the screencast. This way I can make some changes before I start pushing this out more regularly.

In this first episode of Learning Ruby on Rails with Heroku:

  1. Introduction
  2. Goal of this screencast series
  3. What is Heroku?
  4. Getting an account
  5. Creating your first Ruby on Rails application
  6. Basic navigation of Heroku


Learning Ruby on Rails with Heroku Episode 1 from Matthew Carriere on Vimeo.

Using select, reject, collect, inject and detect.

Posted by matthewcarriere

I spend a lot of time convincing my friends to switch to a Mac. Some of my friends are also software developers so naturally, just when they think the evangelism has come to an end, I convince them to get on the Rails. However, learning Rails usually means learning Ruby for the first time as well. In this post I am going to address one of the issues I see for newcomers to Ruby. Looping.

Looping in Ruby seems to be a process of evolution for newcomers to the language. Newcomers will always find their way to the for loop almost immediately and when confronted with iterating an array, the first choice will generally be a for..in:

a = [1,2,3,4] for n in a puts n end

This works, but its not very... Ruby. The next stage of evolution will be using an iterator for the first time. So the for loop gets dropped all together and each is used. The Rubyist is born at this point:

a.each do |n| puts n end

What I see next is a lot of conditional logic being used inside the each block. The logic is generally introduced to perform the following operations:

  1. Building a list of items from an array.
  2. Total the items in an array.
  3. Find an item in the array.

So if this is you, then stop. Ruby has plenty more iterators where each came from. Which one you should be using depends on what operation you are trying to perform. So let's take a look at our previous list and see if we can find a more Ruby way to get them done.

Building a list of items from the array using select

For this operation you should be using select. The way select works is simple, it basically iterates through all the elements in your array and performs your logic on each one. If the logic returns TRUE, then it adds the item to a new array which it returns when the iteration is complete. Here's an example:

a = [1,2,3,4] a.select {|n| n > 2}

This will return the last two elements in the array: 3 and 4. Why? Because 3 and 4 are both greater than 2, which was the logic we placed in the block. It's worth noting that select has an evil step sister named reject. This will perform the opposite operation of select. Logic which returns FALSE adds the item to the array that is returned. Here's the same examples as before except we will swap select, with reject:

a = [1,2,3,4] a.reject {|n| n > 2}

In this example the return value is [1,2] because these elements return false when the condition is tested.

I also have to mention another close sibling to select and reject; collect, which returns an array of values that are the RESULT of logic in the block. Previously we returned the item based on the result of the CONDITION in the block. So perhaps we need square the values in our array:

a = [1,2,3,4] a.collect {|n| n*n}

This returns a new array with each item in our array squared.

Finally, note that using select, reject, and collect returns an array. If you want to return something different, because you are concatenating or totaling values, then check out inject.

Total the items in an array using inject

When you think of accumulating, concatenating, or totaling values in an array, then think of inject. The main difference between select and inject is that inject gives you another variable for use in the block. This variable, referred to as the accumulator, is used to store the running total or concatenation of each iteration. The value added to the accumulator is the result of the logic you place in the block. At the end of each iteration, whatever that value is, can be added to the accumulator. For example, let's sum all the numbers together in our array:

a = [1,2,3,4] a.inject {|acc,n| acc + n}

This will return 10. The total value of all the elements in our array. The logic in our block is simple: add the current element to the accumulator. Remember, you must do something to the accumulator in each iteration. If we had simply placed n in the block the final value of the accumulator would have been 4. Why? Because its the last value in the array and since we did not add it to the accumulator explicitly the accumulator would be replaced in each iteration.

You can also use a parameter with the inject call to determine what the default value for the accumulator is:

a = [1,2,3,4] a.inject(10) {|acc,n| acc + n}

In this example the result is 20 because we assigned the accumulator an initial value of 10.

If you need to return a string or an array from inject, then you will need to treat the accumulator variable that way. You can use the default value parameter of inject to do this:

a = [1,2,3,4] a.inject([]) {|acc,n| acc << n+n}

In this example I add n to itself and then append it to the accumulator variable. I initialized the accumulator as an empty array using the default value parameter.

Find an item in the array using detect

Our last example operation was to find an element in the array. Let's just put it out there and say that other iterators could be used to select the correct value from the array, but I am going to show you how to use detect to round out our exploration of these iterators.

So let's find the value 3 in our array using detect:

a = [1,2,3,4] a.detect {|n| n == 3}

This returns 3. The value we were looking for. If the value had not been found, then the iterator returns nil.

So if your head is spinning at this point as to which iterator to use for when, then remember this:

  1. Use select or reject if you need to select or reject items based on a condition.
  2. Use collect if you need to build an array of the results from logic in the block.
  3. Use inject if you need to accumulate, total, or concatenate array values together.
  4. Use detect if you need to find an item in an array.

By using these iterators you will be one step closer to mastering... Ruby-Fu.

Enter the Get Smart movie contest at Miss604.com

Posted by matthewcarriere

A friend of mine blogs about all the trendy and happening in Vancouver Miss604 ... she runs these movie contests and apparently I have to supply some link love to enter. So here is my entry... I should win by default.

Since this IS a Ruby on Rails blog I figure I should show some code on here:

def enter_contest(choice) @contest.movie_title = choice @contest.save end enter_contest "I want to see Get Smart!"

Installing MySQL on Mac OS X Leopard using MacPorts

Posted by matthewcarriere

There comes a time in every Rails developers life that they need to work with MySQL. Often this means that your development comes to a screeching halt as you wade through the various options for getting MySQL installed on your Mac.

This guide won’t help you install it anywhere else… because I am a zealot and I don’t care how to install it anywhere else.

Install MySQL using macports, go get a coffee while this runs its course.

sudo port install mysql5 +server

Next up, create the initial databases used by MySQL.

sudo /opt/local/lib/mysql5/bin/mysql_install_db --user=mysql

Configure MySQL to start at system start up.

sudo launchctl load -w /Library/LaunchDaemons/org.macports.mysql5.plist

Start MySQL.

sudo /opt/local/bin/mysqld_safe5 &

You can always stop the service manually as well:
mysqladmin5 -u root -p shutdown

Confirm that that MySQL is running.

mysqladmin5 -u root -p ping

Just hit enter at the password prompt, as it is blank. We are about to change that.

Secure your server.

mysqladmin5 -u root password [your password goes here]

At this point you should have your MySQL server up and running. However, your Rails project may complain about not being able to find the socket file. You can find that using the ‘status’ command.

First log into MySQL.

mysql5 -u root -p

At the prompt, run the command.

status;

In the output you will see an entry listing the socket being used by MySQL. You can use this in the database.yml file.

And finally, I really don’t like typing that ‘5’ after all the commands… I can’t explain it, it just upsets me. So I like to create a symbolic link for the mysql5 and mysqladmin5 commands.

sudo ln -s /opt/local/bin/mysql5 /opt/local/bin/mysql sudo ln -s /opt/local/bin/mysqladmin5 /opt/local/bin/mysqladmin

That should get you coding again against a MySQL database!