Rails has_many带有子STI的STI

问题描述 投票:1回答:1

我认为它更像是一个“模型设计”问题,而不是一个rails问题。

为了清楚起见,这里是业务逻辑:我有场地,我想实现多个API来获取有关这些场所的数据。所有这些API有很多共同之处,因此我使用了STI。

# /app/models/venue.rb
class Venue < ApplicationRecord
  has_one :google_api
  has_one :other_api
  has_many :apis
end

# /app/models/api.rb
class Api < ApplicationRecord
  belongs_to :venue
end

# /app/models/google_api.rb
class GoogleApi < Api
  def find_venue_reference
    # ...
  end
  def synch_data
    # ...
  end
end

# /app/models/other_api.rb
class OtherApi < Api
  def find_venue_reference
    # ...
  end
  def synch_data
    # ...
  end
end

那部分有效,现在我想添加的是照片到会场。我将从API获取这些照片,并且我意识到每个API可能都不同。我也考虑过使用STI,我最终会得到类似的东西

# /app/models/api_photo.rb
class ApiPhoto < ApplicationRecord
  belongs_to :api
end

# /app/models/google_api_photo.rb
class GoogleApiPhoto < ApiPhoto
  def url
    "www.google.com/#{reference}"
  end
end

# /app/models/other_api_photo.rb
class OtherApiPhoto < ApiPhoto
  def url
    self[url] || nil
  end
end

我的目标是在最后有这个#tiapp /models/venue.rb类Venue <ApplicationRecord has_one:google_api has_one:other_api has_many:apis has_many:photos:through =>:apis end

# /app/views/venues/show.html.erb
<%# ... %>
@venue.photos.each do |photo|
   photo.url
end
<%# ... %>

而photo.url会给我正确的格式,这取决于api。

随着我在整合方面的深入,似乎有些不对劲。如果我不得不Api has_many :google_api_photo然后每个Api将有GoogleApiPhoto。什么对我没有意义。

知道我该如何从这里开始吗?

ruby-on-rails ruby has-many belongs-to sti
1个回答
0
投票

我想我解决了。

将此添加到venue.rb

has_many :apis, :dependent => :destroy
has_many :photos, :through => :apis, :source => :api_photos

通过调用venue.photos[0].url根据typeApiPhoto字段调用正确的类

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