【发布时间】:2018-10-22 06:36:25
【问题描述】:
我有一个基类 Place 和多个使用 STI 约定的子类。我有一个单独的模型Post,其中belongs_to 是Place 的子类之一:
class Place < ApplicationRecord
end
class SubPlace < Place
has_many :posts, class_name: "SubPlace", foreign_key: "sub_place_id"
end
class Post < ApplicationRecord
belongs_to :sub_place, class_name: "SubPlace", foreign_key: "sub_place_id"
end
可以使用 Rails 控制台保存新的 Post 记录,但在尝试为特定 SubPlace 查找 Posts 时出现以下错误:
ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column places.sub_place_id does not exist)
有没有办法让这个工作,或者我的关联必须只与基类相关?
添加架构:
create_table "posts", force: :cascade do |t|
t.string "title"
t.bigint "sub_place_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["sub_place_id"], name: "index_posts_on_sub_place_id"
end
create_table "places", force: :cascade do |t|
t.string "name"
t.string "type"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
【问题讨论】:
-
错误提示没有列
sub_place_id在位置表中。你有没有? -
@Pavan 列“sub_place_id”在 Posts 表中,因为 Post 属于 SubPlace,或者至少应该属于。出于某种原因,Rails 似乎在此列的 Place 表中查找,我不太清楚为什么。
标签: ruby-on-rails associations single-table-inheritance