ActiveRecord has_one通过关联无法正常工作

时间:2015-03-06 18:24:24

标签: ruby-on-rails activerecord

我有一个SitePlan和一个PriceSchedule应该通过连接表定价。这是我的模特:

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

我不明白为什么当我这样做时出现错误... SitePlan.new.price_schedule

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

模式:

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

1 个答案:

答案 0 :(得分:0)

非常简单的问题,但我会留下我为未来的google发现的东西。

我忘了在SitePlan中指定has_one :pricing关系,在PriceSchedule中指定has_many :pricings关系。显然,这里的魔法比我想象的少,through无法找到对:pricing:pricings的引用,因为我还没有声明它们。