ruby-on-rails - 使用 rails 实现 has_one 多态关联
问题描述
我正在使用 postgis 处理空间数据。
我有一个通用的 poi 表,其中包含名称、地址、经度和纬度等数据
我也在使用friendly_id gem
我想从 Poi 获得住宿、餐饮和城市。
一个Poi有一个住宿或一个餐饮或一个城市
我有很多适用于 Poi 的功能。
我想通过 poi 获取每种类型的数据。
我想我必须建立一个具有 has_one 多态关联的系统......但我不知道,有什么更好的方法。
我想做什么?
通过friendly_id 调用具有不同范围(餐饮、住宿等)的Poi。
例如,我想打电话
Poi.住宿 Poi。城市餐饮
并且,对于每一个,都有一个特殊的渲染。
非常欢迎任何帮助...我是新手...而且我的英语不是更好:(
Poi 型号:
class Poi < ApplicationRecord
extend FriendlyId
friendly_id :name_and_zip_code, use: :slugged
has_one :town, as: poitable
has_one :accomodation, as poitable
城镇模型:
class Town < ApplicationRecord
belongs_to :poitable
end
餐饮模式:
class Accomodation < ApplicationRecord
belongs_to :poitable
end
但我有一个错误,Poi 不能两者兼得.....
编辑 1
我有什么?
class Poi < ApplicationRecord
extend FriendlyId
friendly_id :name_and_zip_code, use: :slugged
geocoded_by :full_address
has_one :town, as: :poitable
has_one :accomodation, as: :poitable
class Accomodation < ApplicationRecord
belongs_to :poitable, polymorphic: true
class Town < ApplicationRecord
belongs_to :poitable, polymorphic: true
在 db:migration 中:
class CreatePois < ActiveRecord::Migration[5.1]
def change
create_table :pois do |t|
t.string :name
t.st_point :lonlat, geographic: true
t.st_point :lonlatheight, geographic: true, has_z: true
t.belongs_to :user, index: true
t.references :poitable, polymorphic: true, index: true
end
end
end
db:migration 住宿
class CreateAccomodations < ActiveRecord::Migration[5.1]
def change
create_table :accomodations do |t|
t.string :genre
end
end
end
db:移民城镇
class CreateTowns < ActiveRecord::Migration[5.1]
def change
create_table :towns do |t|
t.string :department
end
end
end
在 erb 中,我可以创建一个 Poi,但是:
- Poitable_id:无
- Poitable_type : 无
但是,我无法创建城镇或住宿......我有一个回滚:(
我该如何解决?
解决方案
我认为你的模型应该是这样的:
Poi 型号:
class Poi < ApplicationRecord
extend FriendlyId
friendly_id :name_and_zip_code, use: :slugged
has_one :town, as: :poitable
has_one :accomodation, as: :poitable
城镇模型:
class Town < ApplicationRecord
belongs_to :poitable, polymorphic: true
end
餐饮模式:
class Accomodation < ApplicationRecord
belongs_to :poitable, polymorphic: true
end
P/S:有关协会的更多信息。你可以看看这个指南
推荐阅读
- scipy - 错误:Anaconda Jupyter 中的“scipy.misc 模块没有属性 imread”
- javafx - TableCell 中的 JavaFx 文本换行
- javascript - 父组件未将 Firebase 道具传递给子组件
- ios - 当排列视图的大小发生变化时,如何确保 UIStackView 通知它的所有后代?
- android - IDE Android Studio 开始创建新项目时出错
- swift - 所有 videoLayers 显示相同的轨道而不是不同的轨道
- ansible - 如何测试部分输出是否不为空
- c# - 在 EF Core Linq GroupBy 语句中使用前导零格式化日期
- mongodb - 如何在 mongo golang 驱动程序中使用聚合 $facet 查询
- angular - 有没有办法使用变量值在 apollo 客户端上缓存查询结果?