模特是否属于性病儿童?

问题描述 投票:0回答:2

我有一个基类

Place
和多个使用 STI 约定的子类。我有一个单独的模型
Post
,它是
belongs_to
的子类之一:

Place

可以使用 Rails 控制台保存新的 
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

记录,但在尝试查找特定

Post
Posts
时出现以下错误:

SubPlace

有没有办法让这个工作,或者我的关联必须只与基类相关?

添加架构:

ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column places.sub_place_id does not exist)


ruby-on-rails associations single-table-inheritance
2个回答
7
投票

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

这让事情变得美好而简单,因为
class Place < ApplicationRecord end class SubPlace < Place has_many :posts, foreign_key: 'place_id', inverse_of: 'place' end class AnotherKindOfPlace < Place has_many :posts, foreign_key: 'place_id', inverse_of: 'place' end class Post < ApplicationRecord belongs_to :place end

不知道也不关心有不同类型的地方。当您访问

Post
ActiveRecord 会读取
@post.place
列并实例化正确的子类型。
如果 Place 基类也有关联,你只需将其写为:

places.type



2
投票
ActiveRecord::StatementInvalid (PG::UndefinedColumn: 错误: 列 places.sub_place_id 不存在)

您在
class Place < ApplicationRecord has_many :posts, foreign_key: 'place_id', inverse_of: 'place' end

中的关联

无效
。你应该将其重写为 SubPlace

© www.soinside.com 2019 - 2024. All rights reserved.