gpt4 book ai didi

ruby-on-rails - Rails 渲染 json 包括带参数的方法

转载 作者:行者123 更新时间:2023-12-03 16:11:05 28 4
gpt4 key购买 nike

我在方法 Controller 中有这个渲染:

render :json => @boats, :include => {:port => {:only => [:id, :name], :include => {:city => {:only => [:id, :name], :methods => :translatedCity}}}}

但是 translatedCity模型中的方法应该接受语言参数。
  def translatedCity     
language = params[:language]
puts "translatedCity.language=" + language
city = TranslationService.translateCity(self.city_id, language)
return city.element_translation
end

我在 Controller 中有参数。有没有办法把这个参数传递给模型中的方法?

最佳答案

不幸的是,传递需要参数的方法的过程to_json没有很好地内置到 rails 中。一个典型的模式是修改as_json模型上的方法接受自定义键,然后调用 to_json (或 render :json)

# city.rb model
def translatedCity(language)
puts "translatedCity.language=" + language
city = TranslationService.translateCity(self.city_id, language)
return city.element_translation
end

def as_json(options = {})
json_to_return = super
if options.has_key? :translatedCity
city_translation = self.translatedCity(options[:translatedCity][:language])
json_to_return[:translatedCity] = city_translation
end

return json_to_return
end

现在在您的 Controller 中,您可以相应地传递所有内容
render :json => @boats, 
:include => {
:port => {
:only => [:id, :name],
:include => {
:city => {
:only => [:id, :name],
:translatedCity => params[:language]
}
}
}
}

关于ruby-on-rails - Rails 渲染 json 包括带参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30401110/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com