Blinky
Blinky

Reputation: 210

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?

Upvotes: 1

Views: 63

Answers (3)

Blinky
Blinky

Reputation: 210

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. Where feature_id corresponds to the id of the feature in the feature table.

Upvotes: 1

Lordking
Lordking

Reputation: 1413

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

Upvotes: 1

Magnuss
Magnuss

Reputation: 2310

Replace has_one :feature, with belongs_to :feature

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

Upvotes: 1

Related Questions