首页 > 解决方案 > 使用 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,但是:

但是,我无法创建城镇或住宿......我有一个回滚:(

我该如何解决?

标签: ruby-on-railspostgispolymorphic-associationshas-one

解决方案


我认为你的模型应该是这样的:

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:有关协会的更多信息。你可以看看这个指南


推荐阅读