Posts Tagged ‘rails’

Rails Security - SQL Injection - Sanitize User Input!

Thursday, August 21st, 2008

Even though rails makes every effort to help with security in your apps, you should still be proactive about it. Don’t just assume that your data will be safe no matter how you code. Here is a prime example.

You have a login form and you process the request like this:

user = User.find(:first, :conditions=>["login = '#{params[:login]}'"])

You just essentially told every hacker to kill your data by doing something like “‘; delete from users;–”, or even worse a database drop. The appropriate way would be like this:

user = User.find(:first, :conditions=>['login = ?', params[:login]])

Other things you want to make sure you do is to sanitize your views as well:

<%= h @model.value %>

Assume the worse and check all your user input to make sure they can’t do anything you don’t want them to and you will have a happy APP!

Capistrano, CVS, and connection refused issue

Tuesday, August 19th, 2008

If you ever find yourself using CVS as your repository, and are trying to deploy your projects via capistrano, you may run into a connection refused issue.

The easiest way I found a solution around this was to modify the capistrano file: “/capistrano-2.1.0/lib/capistrano/recipes/deploy/scm/cvs.rb”. This of course is in your ruby gems folder.I could have added just the change to my project, but I am lazy, and need this for multiple CVS project deploying from this machine.

The change I made was on line 145, which I added the CVS_RSH=ssh line:

"export CVS_RSH=ssh && mkdir -p #{ dest } && cd #{ dest }"

Simple & Clean Rails Date/Time Format

Monday, July 21st, 2008

Here is a quick, clean and easy way to get use from strftime on your date/time fields. Create a file called date_format.rb in the config/initializers directory and add the following code:

ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS|>.merge!(
   :datetime_military => '%Y-%m-%d %H:%M',
   :datetime          => '%Y-%m-%d %I:%M%P',
   :time              => '%I:%M%P',
   :time_military     => '%H:%M%P',
   :datetime_short    => '%m/%d %I:%M'
)

Then in your views, you can do the following:

@object.time_field.to_s(:datetime)     # Or any other format you created

Rails TypeError (can’t dump File)

Wednesday, June 18th, 2008

For a while, I kept getting exceptions from my app in the form of “TypeError (can’t dump File):”. I finally found out that this was caused when I was using active_record_store with something like file_column, attachment_fu, or paperclip. Basically whenever you’re storing a file in session, that was too large for the session, you would experience this issue. Here is how to get around it:

Say you have a model like so (This is using file_column):

class Model < ActiveRecord::Base
  file_column :filename
end

Then in your controller you would want to add a line before you redirect off to clear that session:

class Controller < ApplicationController
  def create
    @model = Model.find(params[:model])
 
    @model.save!
    params[:model][:filename] = nil rescue nil   # Reset value here
    redirect_to models_path(@model)
  end
end

As you can see, I am resetting the filename value on the model. Now it shouldn’t complain that it can’t dump the file. Happy RAILSING!

Help with Ruby on Rails?

Tuesday, May 20th, 2008

If you come across something that stumps you with ruby or rails, or there is something that you don’t quite understand, let me know. I would love to help out with trying to solve your problem.

Also, if you have something you would like me to explain or create a “how-to” on, let me know about that too. Leave a comment here, or write me an email.
You can contact me at randy@freezzo.com

Rails Unit Test multi-array params

Saturday, May 17th, 2008

While writing some tests the other day, I came across a little bit of a stump. I have an action that required the use of a multi-dimensional param such as:

param[:user][:name]

This is exactly what I was doing, but you get the picture. I could have easily changed it to a single array, but that not the point. The solution in this example, would be to nest your hash in the test such as:

def test_should_do_something
  post :create, :some_object=>{
    :name=>'Bob'
  }, :user=>{ :name=>'Something' }
end

Full message for error_messages_for

Wednesday, May 14th, 2008

I found this somewhere while looking around for the easiest way to provide my own full message for the rails error_messages_for output.

Basically what we are going to do here is provide a humanized string for a variable of the model, and when the error message is printed out, it will display that message. This give more control instead of just having “Email is required.”

class Person < ActiveRecord::Base
 
  HUMANIZED_ATTRIBUTES = {
    :name => "Please provide a name for this person.",
    :email => "You must specify an email address."
  }
 
  def self.human_attribute_name(attr)
    HUMANIZED_ATTRIBUTES[attr.to_sym] || super
  end
 
  validates_presence_of :name,  :message=>''
  validates_presence_of :email, :message=>''
 
end

Override default find conditions for model

Wednesday, May 14th, 2008

Here is a little trick I use when I want to override a find method for a model, instead of adding the conditions option to my association. While I don’t think you should avoid using the conditions options in your associations, this will provide an alternative:

class ModelName < ActiveRecord::Base
  def self.find(*args)
    with_scope(:find=>{ :conditions=>LIMIT_CONDITION }) do
      super(*args)
    end
  end
end

Basically what is happening, is that you are overriding the default find function for a model, and wrapping its own find method with a with_scope call. So now everytime you call Model.find(:all) or whatever options you want, it will execute it under that scope, with the conditions you specify.

Rails Log Analyzer (RAWK)

Saturday, May 3rd, 2008

Came across a sweet rails log analyzer. Doesn’t require that you use syslog or anything like the other log parsers that are out there. This one will work right on your development or production log files. Its called RAWK and you can find it here:

http://rubyforge.org/frs/?group_id=2517&release_id=15246

Application Error - Rails application failed to start properly

Saturday, February 16th, 2008

If you’re like me at all, you have run into this issue many times trying to upload your favorite Rails app to your webhost. This can be a very annoying and painful process if you do not understand what is going on exactly so I am going to outline a few tips to follow when attempting to release your new app, and if those tips do not work, I have my final tip that is actually quite useful.

Here is my checklist:

  • Uncomment ENV['RAILS_ENV'] ||= ‘production’ in environment.rb
  • log and tmp directories have CHMOD 777 access.
  • ALL dispatch files in the public directory are CHMOD 755 at least.
  • Make sure the RAILS_GEM_VERSION is set to something installed on the server.
  • If you have unpacked any custom gems, make sure your app is loading them properly.
  • Make sure any gems you are using are installed on the server.
  • Make sure database.yml file is pointed to correct database.

These usually get the job done, and if you still have issues, feel free to comment here and I’ll try and help.

One thing I have done in that past that helps out really well is to use a “skeleton” app. Basically what I do is the following:

  1. Run rails <appname>_skeleton where your actual app is going to run. This is the app that your domain name will actually use.
  2. Upload the app your working on to some directory on your host.
  3. The key part is here. You are going to symbolically link folders from inside your skeleton app and the folders you would like to do are:
  • app
  • config (Sometimes I link everything inside except the database.yml file and manage it only on the host)
  • db
  • lib
  • test
  • vendor
  • Everything inside public folder except the dispatch files.

This has come in very useful for me as I do not have to worry about permissions on the dispatch files everything I svn up the public directory and my logs are contained by themself. I can also go into my actual app(not the skeleton one) and just run an svn up. You may have to work with the links a little bit to get it working.

If anyone has any comments on this idea or improvements, I would love to hear them.