简体   繁体   中英

ActiveRecord has_one through association not working

I have a SitePlan and a PriceSchedule that should be associated through a join table, Pricing. Here's my models:

class Pricing < ActiveRecord::Base
  belongs_to :site_plan
  belongs_to :price_schedule
end

class SitePlan < ActiveRecord::Base
  has_one :price_schedule, through: :pricings
end

class PriceSchedule < ActiveRecord::Base
  has_many :site_plans, through: :pricings
end

don't understand why I get an error when I do... SitePlan.new.price_schedule

error: ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :pricings in model SitePlan

schema:

create_table "price_schedules", force: true do |t|
  t.boolean  "seasonal"
  t.string   "weekly_discount"
  t.string   "monthly_discount"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "pricings", force: true do |t|
  t.integer  "site_plan_id"
  t.integer  "price_schedule_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "site_plans", force: true do |t|
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
end

Pretty simple question really, but I'll leave what I found for future googlers.

I forgot to specify the has_one :pricing relationship in SitePlan and the has_many :pricings relationship in PriceSchedule. Apparently, there's less magic going on here than I thought, through couldnt find a reference to :pricing or :pricings because I hadn't declared them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM