与rails实现has_one多态关联

时间:2018-06-12 22:55:42

标签: ruby-on-rails postgis polymorphic-associations has-one

我正在使用postgis处理空间数据。

我有一个通用的poi表,其数据为名称,地址,经度和纬度

我也在使用friendly_id gem

我想拥有Poi的住宿,餐饮和城市。

One Poi有一个住宿或一个餐饮或一个城市

我有很多适用于Poi的功能。

我想通过poi获得各种数据。

我认为我必须构建一个具有has_one多态关联的系统......但我不知道,有什么更好的方法。

我想做什么?

通过friendly_id调用具有不同范围(餐饮,住宿等)的Poi。

例如,我想打电话

Poi.accomodation POI。城市 Poi.catering

并且,对于每一个,都要进行特殊渲染。

任何帮助都是非常受欢迎的......我是铁轨上的新手......我的英语并不是更好:(

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 Accomodations

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:nil
  • Poitable_type:nil

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

我该如何解决?

1 个答案:

答案 0 :(得分:0)

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

Poi模特:

Value

城镇模式:

Value

餐饮模式:

class Poi < ApplicationRecord
  extend FriendlyId
  friendly_id :name_and_zip_code, use: :slugged
  has_one :town, as: :poitable
  has_one :accomodation, as: :poitable

P / S:有关关联的更多信息。您可以查看此guides

相关问题