【问题标题】:Rails association through a SHA1 rather than idRails 通过 SHA1 而不是 id 关联
【发布时间】:2011-08-18 17:34:48
【问题描述】:

我正在尝试链接 SHA1 上的两个表,而不是跨表查找 SHA1,并链接通过 id。

我的模型是

类数据集

我尝试使用链接

has_many :datasets, :finder_sql => '选择数据集。* FROM datasets LEFT JOIN dataset_hashes ON datasets.dataset_hash=dataset_hashes.hash WHERE dataset_hashes.hash=#{dataset.dataset_hash}'

但我只是得到一个错误

DatasetHash(#...) 预期,得到 String(#...)

【问题讨论】:

  • 您是否有幸使用:foreign_key 选项来代替?
  • 据我了解,foreign_key 只能让我定义单向关系(除非我理解不正确),所以使用 foreign_key 我可以说 first_table.id 通过 belongs_to first_table 映射到 second_table.other_field, :foreign_key => other_field。我看不出如何在两个非 ID 字段中定义它
  • 在您的情况下,使用非整数主键可能更方便。

标签: ruby-on-rails associations sha1


【解决方案1】:

您可以使用belongs_tohas_many 中的:foreign_key:primary_key

class Dataset < ActiveRecord::Base
   belongs_to :dataset_hash, :primary_key => "dataset_hash", :foreign_key => "hash"
end

class DatasetHash < ActiveRecord::Base
   has_many :datasets, :primary_key => "hash", :foreign_key => "dataset_hash"
end

【讨论】:

    猜你喜欢
    • 2015-07-04
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多