Rails ActiveRecord - is there a way to perform operations on tables without an id?

核能气质少年 提交于 2019-12-07 14:35:29

问题


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:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/825489/rails-activerecord-is-there-a-way-to-perform-operations-on-tables-without-an-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!