Showing posts with label rails. Show all posts
Showing posts with label rails. Show all posts

Wednesday, September 7, 2011

Rails installer 2.0 has been released

RailsInstaller 2.0.0 for Windows has been released! Go read about it at engineyard blog … and download it from railsinstaller.org !

Sunday, September 4, 2011

Duplicate a model in rails 3.1

Ever wanted to duplicate a model in rails ?

This blog post will answer the following issue common to almost all gui. In order to facilitate the life of the administrator, we often see the possibility to duplicate an existing record instead of creating a new one from scratch.

Before rails 3.1, this action was performed using the active-record clone method.

Rails 3.1 is introducing the dup method. Just by it's name, it seems to be the perfect candidate for our task.

How to use it ?

First let's test in the console:

rails c  

a = Model.first # finds the first instance of the model "Model"  
b = a.dup # duplicates the record  
b.save # saves the record into the database.

If you look into your database, you can see that a new record has been created. It is identical to the first record excepted that it has a new id.

You can also modify one of the field of the model to show to the user that he is working with a duplicate and that he has to edit it. I usually prefix the name with "dup_" so I get "dup_Georges" indicating that I need to modify the record.

b.name = "dup_" + b.name

That's it. A simple but very useful method. In my opinion it's the 8th method that has been forgotten in the crud scaffold.

Some details about the implementation:

# ActiveRecord::Base#dup and ActiveRecord::Base#clone semantics have changed to closer match normal Ruby dup and clone semantics.

# Calling ActiveRecord::Base#clone will result in a shallow copy of the record, including copying the frozen state. No callbacks will be called.
# Calling ActiveRecord::Base#dup will duplicate the record, including calling after initialize hooks. Frozen state will not be copied, and all associations will be cleared. A duped record will return true for new_record?, have a nil id field, and is saveable.

Tuesday, April 19, 2011

Thursday, August 12, 2010

How to develop live search textbox in Ruby on Rails

A nice tutorial for a live search textbox using jquery can be found here

Saturday, January 16, 2010

rails and heroku on windows - tutorial

A quick link to install rails and make it work with heroku on windows.

Original post is here

Thursday, December 10, 2009

HTML alternative link to multiple active-record models

The problem :

I needed to display a html link to an active-record model and a specific action in the respective controller only if a given condition was met. I tried to use the rails link_if helper but it was not suitable because I wanted to perform the test on several alternative conditions leading to several alternative links.

In fact, I was building an audit table listing errors coming from several active-record models. I wanted to jump back from the error in the audit table to the original record in the table producing the error. I had one audit table and 6 different tables where the error could come from. In the audit table I had 2 special fields. The first one representing the original ID from the table producing the error. The second one representing the source of data, i.e. the table producing the error.

The solution:

Using the CASE syntax in RUBY I was able to circumvent the problem which puzzled me for a while.

The correct syntax in the view is the following:

<% case  validation.OutputFile 
        when "LIMIT" %>
           <%= link_to image_tag("icons/application_edit.png") , :controller => 'limits' ,:action => "show", :id => validation.Original_id %>
        <% when "COUNTERPART" %>
           <%= link_to image_tag("icons/application_edit.png") , :controller => 'counterparties' ,:action => "show", :id => validation.Original_id %>
        <% when "PROVISIONS" %>
           <%= link_to image_tag("icons/application_edit.png") , :controller => 'provisions' ,:action => "show", :id => validation.Original_id %>
        <% when "NOSTRO" %>
           <%= link_to image_tag("icons/application_edit.png") , :controller => 'nostros' ,:action => "show", :id => validation.Original_id %>
          <% when "OTC" %>
           <%= link_to image_tag("icons/application_edit.png") , :controller => 'derivatives' ,:action => "show", :id => validation.Original_id %>
          <% when "LOANBOOK" %>
         <%= link_to image_tag("icons/application_edit.png") , :controller => 'loanbooks' ,:action => "show", :id => validation.Original_id %>
        <% else %>
         <%=h "-" %>
          <% end %>


Where : 'nostros', 'limits', ... are the names of my controllers where I want to perform the action 'Show' on the original id (id in the table producing the error). "OTC","LIMIT","LOANBOOK",... are the values in the field OUTPUFILE in my audit table indicating the source of data producing the error. validation.OutputFile is the value being evaluated in the WHEN condition.

At the end if no condition is met, I have chosen to display '-' instead of the image link. You could also choose not to display anything or a blank value ''.

Simple and efficient.

Saturday, June 27, 2009

Ext JS 3.0 and rails

Ext JS 3.0, the javascript framework, is now reaching beta 2 with a REST support. This could play along quite well with rails.

Go check it out here

Wednesday, April 8, 2009

Questions on SQL Server adapter

Just a brief post to note that there is a specific discussion group on SQL Server adapter in rails here.

Thursday, January 1, 2009

Learning Ext JS

Packt Publishing recently published a new book Learning Ext JS

This book is well written and examples are easy to follow. although they are using PHP for most of the examples, it is fairly easy to convert to rails. It is a very good and time saving introduction to the Ext JS framework before digging into the official documentation.

Ext Scaffold returns

In a previous post, I spoke about Ext Js scaffolding with the plugin written by Martin Rehfeld

The exact description is the following :

The Ext Scaffold Generator Plugin is a drop-in replacement for Rails’ standard Scaffold Generator. Accepting the very same options, it will generate views using data grid and form components from the Ext JS Javascript GUI framework as well as a controller acting as an Ext-compatible JSON web service. The generated code can be used as a starting point for further implementation and outlines solutions on how to integrate the Ext JS library with Rails as a backend.


you can now find the plugin on github

and install it in your application like this :

ruby script/plugin install git://github.com/martinrehfeld/ext_scaffold.git

More info on GL Network

The advantage of this new version is that all actions happen in the same window (in your index view). The javascript code is now explicit and does not use magic helpers anymore. This is a great improvement. It allows an easy customization of the code and is a great resource to learn how to interact with the Ext JS framework and rails. It also facilitates integration in your current application.

Sunday, November 2, 2008

Using will_paginate for pagination

Since Rails 2.0 the pagination has been removed from the core rails. This allows more flexibility in the choice of the pagination method you want to use.

One secure choice is will_paginate. It is available as a gem

To install the will_paginate gem follow the procedure :

1. rake gems:install
2. gem sources -a http://gems.github.com
3. gem install mislav-will_paginate

The usage of this gem in a project is simple :

1. In your config\environment.rb file add

Rails::initializer.run do |config|
config.gem 'mislav-will_paginate', :version => '~> 2.2.3', :lib => 'will_paginate', :source => 'http://gems.github.com'
end


2. rake gems:install

3. In your controller, replace

@yourmodels = Yourmodel.find

with

@yourmodels = Yourmodel.paginate :page => params[:page], :order => 'created_at DESC'

4. In your index view, add

<%= will_paginate @yourmodels %>

Note : a trick, if it tells you it does not find the method in the controller, configure the gem directly in config\development, test or production file.

Sunday, October 26, 2008

Switching to Thin server

By default, rails uses Webrick which is not particularly efficient. Although a lot of rails sites are using Mongrel in a cluster mode, I've chosen to use Thin.

The installation is really easy :

Yourapplicationdir$\ gem install thin

Then choose the i386 version when asked (at least with such a name, you're sure it's working on Windows).

Usage: thin start instead of the usual ruby script/server start

More information can be found here or on this site.

Sunday, September 7, 2008

Rails against a legacy sql server database

The main problem with legacy database is that you can't do what you want. And there is 99% of chances that your legacy database does not follow the rails conventions.

Here are a few tricks to simplify your life :

1. First of all, SQL Server views are updatable so use them !

ex. create view
as
select mylegacyid as id,
originalcolumn1,
originalcolumn2,
originalcolumn3,
originalcolumn4,
originalcolumn...,
record_creation_date as created_at,
record_modification_date as updated_at

This way your legacy system continues to work correctly and you have a Rails layer built on top using specific views.

Then a trick, as rails builds its indentation on the last record in the database, you must have at least one record in each table otherwise rails won't be able to insert a new record with this method. I've found that this method works well with tables with few fields (25 fields) and saves time.

The other method is to modify the conventions and specify everything (key, table name etc..) manually. If you can't avoid it, here are a few tips :

HowToUseLegacySchemas

Legacy databases

Masking the Database

Rails and Legacy databases

My advice here is to start generating your empty scaffold with the rails convention for your model : ruby script/generate scaffold Car

Then you need to edit the model and indicate the primary key and the table name:

class Car < ActiveRecord::Base
set_table_name "TABLE_VintageCars"
set_primary_key "MyPrimaryKey_Identifier"
end

Then finally update your views. Be carefull with the column names as you know that rails is case sensitive (not like most of your SQL Server or ODBC setup).

This method functions as well and although the creation of new views seems to conform more to the rails philosophy, it might be usefull not to add a ton of new object in your db and to live with existing tables.

Sunday, August 24, 2008

Ext JS 2.0 and rails

I've always wanted a nice Javascript library that I could use as a framework for everything I build. Prototype and Script.a.cul.ous are nice but not sufficient to give the look and feel of a desktop app. So I've decided to implement Ext JS for my solution and to share this experience. There are basically 2 solutions if you want to integrate ext js in your application, the usage of a plugin called ext-scaffold (very easy to use) or the hard-way (manual coding).

Note : The current Rails 2.1 changes the way that rails renders json format. Therefore the plugin ext-scaffold will cease to work out of the box with rails 2.1. This plugin is still functionning perfectly with rails 2.0.2 and remains the fastest way to start playing with ext js and rails.

The plugin gives a good starting point and is functional for simple CRUD application. if you are looking for a quick way to provide a user interface to your tables without exposing the database, it's perfect.

From there, the need to do more complex things arise and then, you guessed it, it's time for the manual coding.

Tuesday, March 25, 2008

Rails 2 and SQL Server 2008 on Windows made simple

I always wondered if rails was really working well with SQL Server. A lot of posts on the web concern every database on earth excepted SQL Server. Most posts concerning SQL Server and Rails are written for previous version of rails and deal with specific issues. And sorry, but the official documentation is the jungle ;-)

So I thought it was time for a simple tutorial on how to use SQL Server and rails 2.0 under MS Windows. The goal of this tutorial is to create a basic CRUD application from scratch. The targeted audience is 0 or little knowledge of rails. I'm using SQL Server 2008 CTP6 but this works as well with other versions of SQL Server (2005 or 2000).

After this simple tutorial, I'll try to go more into details in subsequent posts.

First of all, we have to create our application environment :

1. Open a ruby console, go to your rails_apps directory and type

rails sqlserverapp


This will create your application file (you should see a lot of files preceded by the create statement).

Then you have to install the SQL Server adapter which was removed from the standard rails 2.0 distribution.

2. In the ruby console, type :

gem install activerecord-sqlserver-adapter --source=http://gems.rubyonrails.org


If you have an error message, try to turn off temporarily the windows firewall (the installation won't take more than a few minutes).

Then you have to create a database on your SQL Server

3. Open your SQL Server client tool and create a database called sqlserverapp

4. Add a user with SQL Server authentication called user with secret as password to the database you just created.

5. Create an ODBC link name sqlserverapp to connect to this database.

Then you have to edit your database configuration file to tell rails to use SQL Server and your new database.

6. In the rails console, go to the configuration directory and edit the database.yml file.

cd configuration
edit database.yml


Change the section under development with the following :


development:
adapter: sqlserver
mode: odbc
dsn: sqlserverapp
username: user
password: secret
host: mycomputer


Note : replace mycomputer with the name of your instance of SQL Server (in most cases, locahost should do the job).

Repeat the process for the test and production database if needed.

Then the basic configuration is done. We can start writing the application.

7. In the rails console, to generate the scaffold type :


ruby script/generate scaffold Client name:string address:string email:string remark:text


And ... that's almost finished ! This instruction has done all the work, i.e. created the views, prepared your model, your controller, your test files etc...

You just have to run your db migrations and start your server now.

8. In the rails console, type:

rake db:migrate

This will create your model into SQL Server. If you look into your SQL Server database you should have a table named clients with the columns stated in your scaffold plus two columns for timestamps and one for the primary key which are added automatically.

The last thing you have to do now is to start the web server and test your application.

9. In the rails console, type:

ruby script/server

10. Open your web browser and type:

http://localhost:3000/clients

You should now see a form where you can edit your first client. You can also edit/update/delete any client straight away out of the box.

Yes Ruby on rails is magic ! Remember that the whole application took you 2 lines and 10 minutes to write (spending most of the time reading and watching rails work for you).

So now I can say it ! YES, rails does work simply and efficiently with SQL Server 2008 and active records. It's even very simple to use. I no longer will be a frustrated rails and SQL Server user !