Search code examples
ruby-on-railsrubyactiverecordrails-activerecordrails-migrations

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:

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

and Agency.first.agency_features.first.agencyreturns the correct 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.

How do I make it look for the feature with an id that corresponds to the "feature_id" attribute inside of AgencyFeature?


Solution

  • Maybe try running the migration again. I agree with Marnuss here. I think you don't have the field agency_feature_id in your Feature table. It should look something like -

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