【问题标题】:Active record foreign key primary key issue活动记录外键主键问题
【发布时间】:2021-04-07 14:55:29
【问题描述】:

假设我有两个表,它们通过自定义列链接:

table1s
  id varchar
  user_id varchar

table2s
  id varchar
  linked_user_id varchar

现在,我尝试在 Ruby 代码中建立关​​系

class Table1 < ActiveRecord::Base
    self.primary_key = "id"

    has_many :table2s, primary_key: :user_id, inverse_of: :table1
end

class Table2 < ActiveRecord::Base
    self.primary_key = "id"

    belongs_to :table1, foreign_key: :linked_user_id, inverse_of: :table2s
end

现在,当我尝试进行 SQL 查询时,它出于某种原因使用 id 列而不是指定的 user_id

Table2.select('table2s.*')
          .joins(:table1)
          .where('table1s.id = ?', 323235)

生成的 SQL 如下所示:

SELECT table2s.*
FROM table2s
INNER JOIN table1s ON table1s.id = table2s.linked_user_id
WHERE table1s.id = 323235

我期待它是 user_id 而不是 id

SELECT table2s.*
FROM table2s
INNER JOIN table1s ON table1s.user_id = table2s.linked_user_id
WHERE table1s.id = 323235

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-5


    【解决方案1】:

    如果您有一个自定义关系,其中键与类(表)的 primary_key 不同,那么您需要将 foreign_keyprimary_key 添加到关系中,以便连接正常工作。例如

    class Table1 < ActiveRecord::Base
        self.primary_key = "id"
    
        has_many :table2s, primary_key: :user_id, foreign_key: :linked_user_id, inverse_of: :table1
    end
    
    class Table2 < ActiveRecord::Base
        self.primary_key = "id"
    
        belongs_to :table1, primary_key: :user_id, foreign_key: :linked_user_id, inverse_of: :table2s
    end
    

    belongs_to 来自Docs

    :primary_key 指定返回用于关联的关联对象的主键的方法。默认情况下这是 id。

    has_many 来自Docs

    :foreign_key 指定用于关联的外键。默认情况下,这被猜测为带有“_id”后缀的关联名称。所以定义了belongs_to :person 关联的类将使用“person_id”作为默认的:foreign_key。同样,belongs_to :favorite_person, class_name: "Person" 将使用外键“favorite_person_id”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-05
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多