[英]Rails/ActiveRecord: not retrieving the correct column through a join with a has_one/ belongs_to relationship
Models 楷模
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
Schema 架构
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
The problem 问题
Agency.first.agency_feature
gives me: Agency.first.agency_feature
给了我:
<AgencyFeature id: 508, agency_id: 1, feature_id: 1, enabled: false>
and Agency.first.agency_features.first.agency
returns the correct agency. 和
Agency.first.agency_features.first.agency
返回正确的代理商。
The problem is Agency.first.agency_features.first.feature
gives a column doesn't exist error and is trying to look for "agency_feature_id"
inside of features. 问题是
Agency.first.agency_features.first.feature
给出了一个列不存在错误并且正在尝试在功能内查找"agency_feature_id"
。
How do I make it look for the feature with an id that corresponds to the "feature_id" attribute inside of AgencyFeature? 如何查找具有与AgencyFeature中“feature_id”属性对应的id的要素?
Replace has_one :feature
, with belongs_to :feature
使用
belongs_to :feature
替换has_one :feature
belongs_to :feature
class AgencyFeature < ActiveRecord::Base
belongs_to :agency
belongs_to :feature
end
Maybe try running the migration again. 也许尝试再次运行迁移。 I agree with Marnuss here.
我同意Marnuss的观点。 I think you don't have the field agency_feature_id in your Feature table.
我认为您的功能表中没有字段agency_feature_id。 It should look something like -
它应该看起来像 -
create_table "features", force: true do |t|
t.integer "agency_feature_id"
...
end
I actually figured this one out by changing key attributes in the feature model. 我实际上是通过改变特征模型中的关键属性来解决这个问题。
class AgencyFeature < ActiveRecord::Base
belongs_to :agency
has_one :feature, foreign_key: "id", primary_key: "feature_id"
end
Now I can use the has_one relationship like I intended. 现在我可以像我想的那样使用has_one关系。 Where feature_id corresponds to the id of the feature in the feature table.
其中feature_id对应于要素表中要素的ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.