【发布时间】:2015-05-22 15:06:28
【问题描述】:
我有一个具有这种逻辑的 RoR API:
船长
def index
Lot of stuff...
@boats = query...
render :json => @boats, :include => {:port => {:only => [:id, :name], :include => {:city => {:only => [:id, :name], :include => {:province => {:only => [:id, :name]}}}}}}
end
船模型
belongs_to :port
端口模型
belongs_to :city
等等。
在 BoatController.index 而不是城市中,我想返回翻译后的城市(出于国际化目的)。我不会详细介绍数据库关系(如果需要,请告诉我)。无论如何,我有一项服务可以使用语言和 cityId 参数翻译城市。 所以,我想做这样的事情:
船长:
render :json => @boats, :include => {:port => {:only => [:id, :name], :include => {:translatedCity => [:name], :city => {:only => [:id, :name], :include => {:province => {:only => [:id, :name]}}}}}}
端口模型
def translatedCity
TranslationService.translateCity(self.city_id, lang)
end
belongs_to :city
这是服务方法:
def self.translateCity(cityId, lang)
city = Translation.find_by_sql(["SELECT t.element_translation
FROM translations t, element_types et, languages l, cities c, states s
WHERE et.name = 'City'
AND l.locale = ?
AND c.id = ?
AND t.element_type_id = et.id
AND t.language_id = l.id
AND s.id = c.state_id
AND c.id = t.element_id", lang, cityId]).first
puts "translateCity.city:" + city.inspect
return city
end
查询正在运行,如果我检查结果,我会得到如下信息:
translatedCity.city=#<Translation id: nil, element_translation: "Palma de Mallorca">
但是我收到了这个错误:
TypeError (no implicit conversion of Symbol into Integer):
app/models/boat.rb:29:in `as_json'
app/controllers/boats_controller.rb:253:in `index'
我不知道是否清楚我要做什么。否则,请告诉我,我会澄清的。
【问题讨论】:
-
我会在 City 添加一个
has_many :translations, as: :resource。还有一个belongs_to :resource, polymorphic: true给翻译。这样你就可以简单地查询city.translations.find_by(language: 'de')。 -
如果您在
translations.resource_id上创建索引,那么复杂性会大大降低,查询也会快很多。
标签: ruby-on-rails ruby-on-rails-4