我认为这更像是一个“模型设计”的问题,而不是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我的目标是在最后实现这一点# /app/models/venue.rb class Venue < ApplicationRecord has_one :google_api has_one :other_api has_many :apis has_many :照片:通过=>:api结束
# /app/views/venues/show.html.erb
<%# ... %>
@venue.photos.each do |photo|
photo.url
end
<%# ... %>而且photo.url会给我正确的格式化,这取决于它是什么。
随着我对集成的深入研究,似乎有些地方不太对劲。如果我必须Api has_many :google_api_photo,那么每个Api都会有GoogleApiPhoto。对我来说没什么意义的。
你知道我该怎么做吗?
发布于 2017-12-26 00:21:22
我想我已经解决了。
通过将此代码添加到venue.rb
has_many :apis, :dependent => :destroy
has_many :photos, :through => :apis, :source => :api_photos通过调用venue.photos[0].url,根据ApiPhoto的type字段调用正确的类
https://stackoverflow.com/questions/47969048
复制相似问题