【问题标题】:Rails ActiveRecord - is there a way to perform operations on tables without an id?Rails ActiveRecord - 有没有办法对没有 id 的表执行操作?
【发布时间】:2009-05-05 15:40:16
【问题描述】:

我有一张一排两列的表格-

int 'version', datetime 'updated'

是否有 Rails ActiveRecord 方法来获取和设置这些列中的数据? 没有 id 列。

我正在使用此表来跟踪其他表的查询版本。每次查询另一个表后,版本列都会增加,更新的列设置为当前日期时间。

【问题讨论】:

  • 我的目的是让这个表的工作方式类似于 Rails 使用“schema_info”表跟踪迁移版本的方式。
  • 我已经发布了一个关于这个主题的博客:ho.race.hk/blog/?p=208

标签: mysql ruby-on-rails ruby activerecord


【解决方案1】:

在您的模型类中,使用self.primary_key = "primary_key_column" 指定要用作主键列的列。我想在你的情况下你可以使用版本列。

【讨论】:

    【解决方案2】:

    没有什么可以阻止你在没有 ID 的情况下在 ActiveRecord 中使用它:

    迁移包含:

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

    查询:

    >> 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">]
    

    日志报告这些 SQL 请求:

    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) 
    

    希望有帮助

    【讨论】:

    • 我不知道它是这样工作的。酷的东西。虽然,我认为更新或删除不会按预期工作,因为这些操作依赖于现有的主键。
    • .all 是 .find(:all) 的别名。由于缺少 id,使用大多数其他参数来 .find 会导致错误。
    【解决方案3】:

    当没有 id 列时,Rails 唯一可以使用的是 has_and_belongs_to_many 连接表。

    否则,您必须使用纯 SQL,例如:

    SomeModel.connection.execute "select * from mytable"
    

    或者如果 version 打算作为主键,请使用 John 的答案。

    【讨论】:

      猜你喜欢
      • 2019-09-07
      • 1970-01-01
      • 2011-04-15
      • 2013-05-12
      • 2013-10-10
      • 2014-07-16
      • 2015-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多