Monday, January 31, 2011

Restful routes for non ID( primary key ) rails 3

Lets suppose that you have a Profile model, and  you have a resources :profiles route.

Generally, profile_path will build a path with the profile object’s ‘id’ in it:
profile = profile.find_by_name('jaganreddy')
  profile_path(profile)  # => "/profiles/1"
You can override to_param in your model to make profile_path build a path using the profile’s name instead of the profile’s id:
class Profile < ActiveRecord::Base
    def to_param # overridding default behaviour
       name 
    end
 end
    
  

  profile = Profile.find_by_name('jaganreddy')
  profile_path(profile)  # => "/profiles/jaganreddy" 
 
Also take care for nested resources too
In your controller always looks for  
Profile.find_by_name(params[:id])

Wednesday, January 26, 2011

how to set primary key and autoincrement on non id column using rails 3 -- sqlite

sqlite_adopter uses
       def default_primary_key_type
          if supports_autoincrement?
            'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL'
          else
            'INTEGER PRIMARY KEY NOT NULL'
          end
        end
and under the create table definition the line says:
table_definition.primary_key(options[:primary_key] || Base.get_primary_key(table_name.to_s.singularize)) unless options[:id] == false

that means we should not set :id => false ... many people will do to avoid id column..  this is fine
but if you want  other column as primary key add at table definition not at column definition.(dont add :id => false)..

adding primary_key at table definition will take care of removing id column.  the following line will also add t ocolumn definition
  'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL'
 ofcourse based on sqlite3 version...

      def supports_autoincrement? #:nodoc:
        sqlite_version >= '3.1.0'
      end
 Note: so autoincrement for :primary_key is hard coded
sample:
create_table :students, :primary_key => student_id do |t|
   t.string :name
end
it generates students table as follows;
  students;
                  student_id : primary key autoincrement
                 name :   varchar


This is for what i am using version of rails : 3.0.3

Monday, January 10, 2011

undefined method `user_signed_in? with Rails 3.0.3 - Devise

I just started a new rails 3.0.3 application after doing a gem update
(loaded rails 3.0.3 and devise 1.1.5) and I got the same error. This
was following the default devise install instructions.

answer:
for got to add
devise_for :users in routes.rb