Refactor your controller code by using postbacks
It is very easy to end up with an action for every single request. You may find you generate a controller like this for example:
./script/generate controller User create_form, create, edit_form, edit
It is not necessary to have 4 actions here. Instead this can all be handled by the same action:
def update
@user = User.find_by_id(params[:id]) || User.new
if request.post?
@user.attributes = params[:user]
if @user.save
redirect_to :action => 'index'
return
end
end
end
On first calling the action there is no data, and the template with your form is displayed. Once the form is submitted to the same action, the user object is saved and the controller redirects to the home page (or the page of your choice).
Using ActiveRecord to store session information in Ruby on Rails
Rails default setting is to store sessions on the file system. This is fine during development, but this is not very scalable once an application goes into production. Often the application will be deployed to a number of servers. One good solution to is to use ActiveRecord to store the session information in the database. Fortunately this is very easy to do!
First of, open the config/environments.rb file and uncomment the following line:
config.action_controller.session_store = :active_record_store
Now we create the sessions table. There is already a rake task for doing this:
rake db:sessions:create
rake db:migrate
Now restart your server and voila! Rails does not automatically manage sessions so it is worth noting that you will need to deal with this. If you do not you could end up with a sessions table with millions of rows. This will slow your application down considerably. I will post more information soon on sweepers and dealing with session expiry.