views:

741

answers:

4

I have a table with one row and two columns-

int 'version', datetime 'updated'

Is there a Rails ActiveRecord way to get and set the data in these columns? There is no id column.

I'm using this table to track versions of queries of other tables. After each query of another table the version column is incremented and the updated column is set with current datetime.

+1  A: 

The only thing Rails works with, when no id column is present, is a has_and_belongs_to_many join table.

Otherwise you have to drop down to pure SQL, with something like:

SomeModel.connection.execute "select * from mytable"


Or if version is intended to be the primary key, use John's answer.

Squeegy
+4  A: 

In your model class, use self.primary_key = "primary_key_column" to specify the column to use as the primary key column. I guess that in your case you could use the version column.

John Topley
+2  A: 

Nothing prevent you to use it in ActiveRecord without ID :

The migration contains :

create_table :posts, :id => false do |t|
  t.integer :version
  t.datetime :updated
end

Queries :

>> Post.create(:version => 1, :updated => Time.now)
=> #<Post version: 1, updated: "2009-05-05 19:24:31">
>> Post.all
=> [#<Post version: 1, updated: "2009-05-05 19:24:31">]
>> Post.all(:conditions => { :version => 1 })
=> [#<Post version: 1, updated: "2009-05-05 19:24:31">]

The log report these SQL requests :

CREATE TABLE "posts" ("version" integer, "updated" datetime) ;
INSERT INTO "posts" ("version", "updated") VALUES(1, '2009-05-05 19:24:31');
SELECT * FROM "posts" 
SELECT * FROM "posts" WHERE ("posts"."version" = 1)

Hope that helps

tal
I didn't know it worked like that. Cool stuff. Although, I would imagine an update or delete wouldn't work as expected since those operations depend on an existing primary key.
Squeegy
.all is an alias to .find(:all). Using most other parameters to .find will result in a error due to the lack of an id.
daustin777
A: 

I have put up a blog on this topic: http://ho.race.hk/blog/?p=208

ohho