Rails / ActiveRecord:不通过has_one / belongs_to关系的连接检索正确的列

时间:2015-10-18 21:07:01

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

模型

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.agency会返回正确的代理商。

问题是Agency.first.agency_features.first.feature提供列不存在错误,并且正在尝试在功能内查找"agency_feature_id"

如何查找具有与&#34; feature_id&#34;相对应的ID的功能?在AgencyFeature中的属性?

3 个答案:

答案 0 :(得分:1)

has_one :feature替换为belongs_to :feature

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

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

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

现在我可以像我想的那样使用has_one关系。其中feature_id对应于要素表中要素的ID。