Rails/ActiveRecord:未通过具有 has_one/belongs_to 关系的联接检索正确的列

Rails/ActiveRecord: not retrieving the correct column through a join with a has_one/ belongs_to relationship

型号

class Feature < ActiveRecord::Base
  belongs_to :agency_feature
  ...
end

class Agency < ActiveRecord::Base
  has_many  :agency_features, dependent: :destroy
  ...
end

class AgencyFeature < ActiveRecord::Base
  belongs_to :agency
  has_one :feature
end

架构

create_table "agency_features", force: true do |t|
  t.integer "agency_id"
  t.integer "feature_id"
  t.boolean "enabled"
end

add_index "agency_features", ["agency_id"], name: "index_agency_features_on_agency_id", using: :btree
add_index "agency_features", ["feature_id"], name: "index_agency_features_on_feature_id", using: :btree

问题

Agency.first.agency_feature 给我:

<AgencyFeature id: 508, agency_id: 1, feature_id: 1, enabled: false>

Agency.first.agency_features.first.agencyreturns正确的机构。

问题是 Agency.first.agency_features.first.feature 给出了 列不存在 错误,并试图在特征中寻找 "agency_feature_id"

如何让它查找 ID 与 AgencyFeature 内的 "feature_id" 属性相对应的特征?

has_one :feature 替换为 belongs_to :feature

class AgencyFeature < ActiveRecord::Base
  belongs_to :agency
  belongs_to :feature
end

或许可以再次尝试 运行 迁移。我同意 Marnuss 的观点。我认为您的功能 table 中没有字段 agency_feature_id。它应该看起来像 -

create_table "features", force: true do |t|
  t.integer "agency_feature_id"
  ...
end

我实际上是通过更改特征模型中的关键属性来解决这个问题的。

class AgencyFeature < ActiveRecord::Base
  belongs_to :agency
  has_one :feature, foreign_key: "id", primary_key: "feature_id"
end

现在我可以按预期使用 has_one 关系了。其中feature_id对应特征中特征的idtable.