Archive for the ‘Ruby on Rails’ Category

NameError after the Upgrade to Rails 2.3.2

Tuesday, April 21st, 2009

I was upgrading my local rails version from 2.2.2 to 2.3.2 by running:

gem update

I changed config/environment.rb to:

RAILS_GEM_VERSION = ‘2.3.2′ unless defined? RAILS_GEM_VERSION

Starting my local server and navigating to localhost:3000 produced the following error:

NameError in UsersController#login
uninitialized constant ApplicationController

Obviously, Google to the rescue (again)… :)

I found a post from http://giantrobots.thoughtbot.com/2009/4/15/rails-2-3-2-upgrade-gotchas

The solution is to rename controllers/application.rb to controllers/application_controller.rb.

Matt has a lot more tips for upgrade, so I recommend reading his post.

Reset Button in Rails

Sunday, August 3rd, 2008

I am sure at some point web applications will require an entry form.

I just notice that Rails does not make the ‘Reset’ button available. Here is an example of an HTML form with a reset button:

Google helps me again! :)

I found a post from mc-kenna.com to describe what needs to be done.

<%= submit_tag "Start over", :name => ‘reset’, :type => ‘reset’, :id => ‘task_reset’ %>

Upon further research, I found an interesting discussion/ticket about making the reset button available in Rails. Making the button available is considered as a bad practice.

The ticket refers to Jacob Nielsen’s useit.com. A little blurb:

The Web would be a happier place if virtually all Reset buttons were removed. This button almost never helps users, but often hurts them.

I agree with the opinion that the button should be removed! :)

How to Debug in Rails

Saturday, June 14th, 2008

Every developers need debuggers now and then. I have been using ruby-debug for a while now.

You can check whether you have ruby-debug installed:

gem list ruby-debug

If you do not have ruby-debug installed, you can run the following command:

gem install ruby-debug

I have been using Mongrel for my development. To enable debugging, you should start your server with –debug option:

ruby script/server –debug

To stop at a certain point in your code, all you need to do is to add a ‘debugger’ line:

  def edit
    @task = Task.find(params[:id])
    debugger
    current_user_id = find_current_user_id()
  end

Once your application reach the ‘debugger’ line, the server window will turn into:

(rdb:10)

To check for a variable value, type:

pp @task

You can explore other commands easily by typing ‘help’.

(rdb:10) help
ruby-debug help v0.10.1
Type ‘help <command-name>’ for help on a specific command


Available commands:
backtrace  delete   enable  help    next  quit     show    trace
break      disable  eval    info    p     reload   source  undisplay
.
.

Happy debugging! :)

Rails Date Validation – Step by Step

Monday, May 26th, 2008

Update 5/31/2008: Use ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS

I have invested some time to get Rails date validation to work (whoo hoo!).

Without further ado, here are the step by step instructions:
1. Download Rails Date Kit from my site. Note that I got the original kit from http://www.methods.co.nz/rails_date_kit/rails_date_kit.html.
Extract the files in rails_date_kit_1.2.0.tar.gz to <your application>/vendor/plugins/rails_date_kit.
Rails Date Kit

2. Get the Validates Date Time plugin by running the following command in your application directory:

script/plugin install http://svn.viney.net.nz/things/rails/plugins/validates_date_time

You should have a new directory in your <your application>/vendor/plugins/validates_date_time
Validates Date Time-1

3. Put the necessary files in the right places.

Copy vendor/plugins/rails_date_kit/calendar.js to public/javascripts
Copy vendor/plugins/rails_date_kit/calendar.css to public/stylesheets
Copy vendor/plugins/rails_date_kit/calendar_prev.png to public/images
Copy vendor/plugins/rails_date_kit/calendar_next.png to public/images
Copy vendor/plugins/rails_date_kit/date_helper.rb to app/helpers


4. Include the css and javascript files for the calendar in your page header (e.g. view/layout/tasks.html.erb):

<%= stylesheet_link_tag ‘calendar.css’ %>
<%= javascript_include_tag ‘calendar’ %>

My application uses application.rhtml, thus I just added the lines there.

5. Create a new file called date_formats.rb in config/initializers. All you need to add is:

ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(:default_date => ‘%m/%d/%Y’)

Note the capital Y in ‘%m/%d/%Y’. Obviously, you can add more date formats as needed.
Update: Adjust the date format accordingly to your locale. For example, use ‘%d/%m/%Y’ for displaying date/month/year.

6. Use the following code to add the date field in your input form (e.g. view/tasks/new.html.erb):

<%= date_field :task, :due_date, :format => ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS[:default_date], :value => @task.due_date %>

You can also wrap the whole ‘ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS[:default_date]‘ into a function in app/helpers/application_helper.rb.

6. Tell your model to use en-us date format by adding the following line:

ValidatesDateTime.us_date_format = true #use mm/dd/yyyy format

Update: Set ValidatesDateTime.us_date_format to ‘false’ if your date format is not month/date/year.

7. Validate away! :)
Here’s an example of my model validation:

Class Task < ActiveRecord::Base
.
.
validates_date :due_date, :allow_nil => true
.
.
End


Enjoy! :)

Post any questions in the comment.

Switch (Upgrade?) My Web Application to Use Rails 2 (2.0.2)

Friday, April 4th, 2008

My web application was using Rails 1.2.6. I decided to upgrade my application to use Rails 2.0.2.

I simply changed ‘1.2.6′ to ‘2.0.2′ in config/environment.rb:

RAILS_GEM_VERSION = ‘2.0.2′ unless defined? RAILS_GEM_VERSION #*handy – Use Rails 2.0.2 now from 1.2.6

It was time to fire up my application and I got the following warning:

*******************************************************************
* config.breakpoint_server has been deprecated and has no effect. *
*******************************************************************

I fixed the problem by commenting out the line in config/environments/development.rb:

# Enable the breakpoint server that script/breakpointer connects to
#config.breakpoint_server = true #*handy – Unused for Rails 2.0.2

Obviously, I put my comment there at the end… :)

One down… I fired up the server and got a hard error:

/!\ FAILSAFE /!\ Thu Apr 03 18:57:55 -0500 2008
Status: 500 Internal Server Error
A secret is required to generate an integrity hash for cookie session data. Use config.action_controller.session = { :session_key => “_myapp_session”, :secret => “some secret phrase of at least 30 characters” } in config/environment.rb

There was a little hint in the error message. I added the suggested line in config/environment.rb:


Rails::Initializer.run do |config|
   #*handy – Needed for Rails 2.0.2
   config.action_controller.session = { :session_key => “_myapp_session”, :secret => “some secret phrase of at least 30 characters” }

There was a :secret symbol which I changed to (obviously) something secret. :)

I recommend GRC’s Ultra High Security Password Generator for a good random string.

If you have a saved session before, be sure to clear it up by running “rake tmp:sessions:clear”.

Post in the comments if you have any question.

Rails Symbols

Sunday, February 24th, 2008

It is very important to understand symbols and how it behaves in Rails. Symbols concept was very confusing for me before. Again, Google to the rescue! :)

I found a good article from Gluttonous that explains how symbols work.

As I progress through Agile Web Development with Rails, I notice that symbols and strings can be used interchangeably in most cases. For example:

redirect_to(:action => “index”)
redirect_to(:action => :index)

Rails 2.0.2 Uses SQLite3 by Default?

Monday, January 21st, 2008

I just upgraded to Rails 2.0.2 by running:

$gem update rails

I started my new Rails project. The content of config/database.yml surprised me!

development:
adapter: sqlite3
database: db/development.sqlite3
timeout: 5000

I used Google to search for the change and found Rob’s post.

Here I am using MAMP as my MYSQL database provider so far. So, I have to try it out. :)

I quickly whipped up a test project and created a new model.

$rails test
$ruby script/generate model product

I modified db/migrate/001_create_products.rb to add one column only:

create_table :products do |t|
t.column :name, :string
end

Finally…

$rake db:migrate
== CreateProducts: migrating ==================================================
– create_table(:products)
-> 0.0033s
== CreateProducts: migrated (0.0035s) =========================================

The first thing that came to my mind is “SWEET!!!” :)

Although Mac has SQLite3 by default, Windows users may not. The good news is that Rob also has the solution.

I think this is a good news for users that have sqlite3 installed by default because there is one less thing to setup. Also, using SQLite3 makes the development directory more compartmentalized.

After playing around with the database a little bit, I don’t like how data is shown in the query. Each field is delimited by a pipe character.

$sqlite3 db/development.sqlite3
sqlite> select * from products;
1|Test Product

I can’t seem to find a Mac-based tools to maintain SQLite3 database. Also, I don’t want to install/configure web-based tools if one is available.

I’ve decided that I’m going to stay with MYSQL for now due to more mature tools (that I can use to view my MYSQL database).

rails -d mysql myapp

Ruby on Rails: Date and Time Validation

Tuesday, December 4th, 2007

Update May 26th, 2008: I have posted new instructions to validate dates in Rails.

I am working on my Rails project and need a date validation in the model.

I found Validates Date Time Plugin.

According to RailsLodge Plugin page, I can automatically download the whole branch by issuing the following command:

ruby script/plugin install http://svn.viney.net.nz/things/rails/plugins/validates_date_time/

The resulting files should be stored in the vendor/plugins/validates_date_time.

Once I have more time, I’ll be sure to give it a spin. :)

Ruby on Rails: NoMethodError in Controller#action – Undefined method ‘each’

Tuesday, November 27th, 2007

I set an instance variable by running the following query:

@some_list = Model.find_by_column_name(nil)

I tried to interate the content of @some_list and received the following error:

NoMethodError in Controller#action

Showing app/views/model/list.rhtml where line [line number] raised:

undefined method `each’ for #…

Apparently, I just need to add “_all_” in the query:

@some_list = Model.find_all_by_column_name(nil)

Easy solution, eh? :)

Update: I found the solution after I looked at the back-end SQL query.

Task Load (0.000354) SELECT * FROM table WHERE [some condition] LIMIT 1

After I added “_all_” in the statement, I finally get the right query.

Task Load (0.000332) SELECT * FROM table WHERE [some condition]

Rails Database Convention

Thursday, November 22nd, 2007

I finally start to create my own Rails application and it is not easy to remember all the RoR conventions.

Raaum.org has a very good database conventions that RoR (*cough*) “recommends.”

Obviously, I use Locomotive for my Rails development. :)

Thank you, Ryan! :)