Reputation: 12738
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.
Upvotes: 3
Views: 2739
Reputation: 3433
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
Upvotes: 4
Reputation: 115322
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.
Upvotes: 7
Reputation: 187014
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.
Upvotes: 1