【发布时间】:2017-03-02 20:41:16
【问题描述】:
我的模型中有 2 个非数据库属性。如果其中一个有值,我需要在 json 响应中返回另一个:
class Car < ApplicationRecord
attr_accessor :max_speed_on_track
attr_accessor :track
def attributes
if !self.track.nil?
super.merge('max_speed_on_track' => self.max_speed_on_track)
end
end
end
问题在于'if !self.track.nil?'这一行当控制器尝试返回 json 时抛出错误
也许有更好的方法,因为我读到使用 attr_accessor 是一种代码味道。
我想要做的是,如果用户将跟踪值作为查询参数传递给我,然后我将该值传递给模型并使用它来计算 max_speed_on_track,并返回该值。
显然,如果用户没有提供任何曲目,那么我不想在 json 中返回 max_speed_on_track。
控制器方法现在非常基本(我仍然需要添加检查轨道参数的代码)。代码在保存行抛出错误。
def create
@car = Car.new(car_params)
if @car.save
render json: @car, status: :created
else
render json: @car.errors, status: :unprocessable_entity
end
end
【问题讨论】:
-
如果这只是你调用
to_json的时候,为什么不重写as_json方法而不是attributes方法呢?此外,您可以使用if track.present?,而不是使用if !self.track.nil?。它更容易阅读。 -
谢谢,但如果 self.track.present?抛出同样的错误
-
我在jonathanjulian.com/2010/04/rails-to_json-or-as_json 上读到了关于 as_json 的内容,但我仍然卡住了。当 track 不为 null 时,我在 as_json 方法中包含我想要的字段,但当 track 有值时排除它。
标签: ruby-on-rails json attr