Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top