Connect Rails 4 With Microsoft SQL Server Database

31 sec read

I spent a while to find a solution for connecting Rails 4 with MS SQL Server database. Later I found a quick and easy solution via tiny_tds for my Ubuntu platform.
The gem tiny_tds is a good replacement for RubyODBC/unixODBC/iODBC/AnyODBC.
Step 1: Simply tidy_tds and activerecord-sqlserver-adapter into your Gemfile
[source language=”ruby”]
gem ‘tiny_tds’
gem ‘activerecord-sqlserver-adapter’, git: ‘git@github.com:nextgearcapital/activerecord-sqlserver-adapter.git’, :branch => “rails-4”
[/source]
Step 2: Edit config/database.yml to map your SQL Server database locations
[source language=”ruby”]
development:
adapter: sqlserver
host: dbhost.com
mode: :dblib
database: database_name
username: user
password: pass
[/source]
Step 3: Install free tds (for Ubuntu only).
Install free tds from http://www.freetds.org/.
Extract downloaded tgz file and do
[source]
sudo ./configure
sudo make
sudo make install
[/source]
Step 4: Do bundle install on your rails 4 web app and run your Rails application.
Thats it. Enjoy.

Related posts:

6 Replies to “Connect Rails 4 With Microsoft SQL Server Database”

  1. I’ve set up a clean Rails 4.0.2 app with SQLServer adapter, but when trying to fetch some objects, I’m getting this:
    > Contact.count
    SQL (1.1ms) USE [c4_immo]
    (1.9ms) EXEC sp_executesql N’SELECT COUNT(*) FROM [Contact]’
    => 4836
    > Contact.first.attributes
    Contact Load (77.1ms) EXEC sp_executesql N’SELECT TOP (1) [Contact].* FROM [Contact] ORDER BY [Contact].[CID] ASC’
    NoMethodError: undefined method `[]’ for nil:NilClass
    While Rails seem to be able to connect and return the count, it can’t read any attributes. Did you have similar problems?

  2. It works fine for me.
    Contact.first.attributes
    [1mEXEC sp_executesql N’SELECT TOP (1) [contacts].* FROM [contacts] ORDER BY [contacts].[id] ASC’?[0m
    => {“id”=>2, “name”=>”Josh”,…….}

  3. I tried to implement this gem, but I have dependencies issues (on RoR 4.0):

    Bundler could not find compatible versions for gem “arel”:
    In Gemfile:
    activerecord-sqlserver-adapter (~> 4.0.0) x86-mingw32 depends on
    arel (~> 4.0.1) x86-mingw32
    arel (4.0.0)

    I tried to remove activerecord and arel in order to install arel 4.0.1 and activerecord 4.0.4, but the result is still the same.
    Any suggestion ?
    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *