Easy True/False Select Tag with Rails

Posted by Randy on December 22, 2008

It’s been a while since my last post. I have been pretty busy with other things, but thats no excuse. Anyway, I came across a problem where I needed to create a select tag with just a true and false option in it and came up with the following quick and easy solution. (This would presumably work with more/different options as well):

First, create a file in the config/initializers directory. This is where your global variables will go for use in the select tags. I called mine select_tag_globals.rb:

TRUE_FALSE = { 'True'=>true, 'False'=>false }

Make sure the values are set to whatever the fields data type is. In this case I want the labels to say True or False, and the value saved to the database will be true or false. Now all we have to do is use this in a select tag in a view like so:

<%= f.select :database_field, TRUE_FALSE %>

This should give you a normal select box with True and False labels. Yay rails!

ActiveRecord and Transactions!

Posted by Randy on October 29, 2008

If you ever have to do multiple actions with activerecord, you should group it into a transaction like so:

Post.transaction do
  posts.each do |post|
    post = Post.new(:body=>'Whatever')
    post.save!
  end
end

This will rollback too if the save fails.

Bulk update using ActiveRecord without SQL!

Posted by Randy on October 23, 2008

Here is a cool way you can update columns in a table without writing any SQL using ActiveRecord. Suppose you have a form with checkboxes that are for deleting posts for the ones that are checked:

<input type="checkbox" name="posts[]" value="<%= post.id %>">

Now you can update this in the method of your controller that this form posts to:

Post.update_all({:removed=>true}, {:id=>params[:posts]})

ActiveRecord will take of the fact that you want to update 1 record or multiple!

ActiveRecord counting with associations 1

Posted by Randy on October 22, 2008

The other day I had to display the number of children items an object had so I decided to do the following:

# Controller
@customers = Customer.find(:all, :include=>[:receive_payments])
 
#View
<%= customer.receive_payments.count %>

While this worked for what I needed, it executed the following sql every iteration:

SELECT count(*) AS count_all FROM "receive_payments" WHERE ("receive_payments".customer_ref_list_id = E'850000-1071531366')

I thought this wasn’t right considering I used an association, however when you use count, it forces the use of count(*) on the database. This is where size comes in!!!!

<%= customer.receive_payments.size %>

Now we get the same results without the extra database counts!

Easy Hash to XML and back conversion in Ruby 2

Posted by Randy on October 08, 2008

Instead of spending hours trying to write something custom to convert your hash into xml or vice versa, you can do it in one line. If you are already in a Rails environment, you are good to go, but if using ruby, include the ActiveSupport gem:

require 'rubygems'
require 'active_support'

Now that you have, we can convert a xml to a hash:

hash = Hash.from_xml(xml_stream)

And a hash to xml is stupid simple:

xml = hash.to_xml

There you have it, simple xml to hash and hash to xml!

Squidoo, Clickbank and marketing?

Posted by Randy on September 24, 2008

I have decided to take a stab at using squidoo effectively, while promoting a clickbank product to hopefully make some sales. I was over at potpiegirl.com and her posts really inspired me to try harder. I contacted her and asked her for some tips, which she gladly helped out with.

I pulled together a squidoo lens, which that in itself can be overwhelming, and came up with a page promoting creating free electricity. I am no expert, so I’m not even sure if what I’m doing will work. Hopefully it works out well!

On a side note, you can follow me on twitter :)

Do you has a force field? 2

Posted by Randy on September 23, 2008

Couldn’t help it, but this made me laugh. Got the same response from co-workers I passed it around to:

I has a force field

Restful Authentication and Basic HTTP Auth

Posted by Randy on September 23, 2008

I had an application that was prompting a HTTP Authentication box in IE after using the restful authentication plugin. The way I fixed it was to replace the access_denied method in lib/authenticated_system.rb to:

def access_denied
  respond_to do |format|
    format.any do
      #format.html do
      store_location
      redirect_to new_session_path
    end
    #format.any do
      #  request_http_basic_authentication 'Web Password'
    #end
  end
end

Noticed I commented some lines out. This was so that if i ever need to revert, the code will still be there and I wont have to go looking for it. Hope this helps!

Rails route helpers – route_url vs route_path

Posted by Randy on September 10, 2008

If you weren’t already aware of this, there IS a difference between using route_url and route_path. Here are what they return:

<%= posts_url %>  # => http://localhost:3000/posts
<%= posts_path %> # => /posts

As a general rule of thumb, you would want to use posts_url in your controllers, and posts_path in your views.

href jumps to top of page 2

Posted by Randy on September 09, 2008

While this isn’t a ruby on rails specific issue, I do tend to do this a lot, and never thought twice about it, until it starts bugging the crap out of me.
The issue is that you have a link that is used to do some type of javascript, instead of linking. So you add an onclick event, but you need something to link to. I usually put in a # sign:

<a href="#" onclick="dosomething();">Do Something</a>
<%= link_to 'Do Something', '#', :onclick=>'dosomething()' %>

This is great, except that it jumps you to the top of the page. Very annoying. Here is the solution:

<a href="#nogo" onclick="dosomething();">Do Something</a>
<%= link_to 'Do Something', '#nogo', :onclick=>'dosomething()' %>

Notice I added “nogo” to my #. This will help prevent from jumping to the top of the page. You can of course use any text you want there.