[英]Rails 5: attr_accessor throwing NoMethodError (undefined method `keys' for nil:NilClass):
I have 2 non database attributes in my model. 我的模型中有2个非数据库属性。 If one of them has a value, I need to return the other one in the json response: 如果其中一个具有值,则需要在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
The problem is that the line 'if !self.track.nil?' 问题是“ if!self.track.nil?”行是 throws an error when the controller tries to return the json 控制器尝试返回json时引发错误
Perhaps there is a better way as I read that using attr_accessor is a code smell. 当我读到使用attr_accessor是一种代码味道时,也许有更好的方法。
What I am trying to do is if the user passes me a track value as a query parameter, then I pass that value to the model and it uses it to calculate the max_speed_on_track
, and return that value. 我要尝试执行的操作是,如果用户将跟踪值作为查询参数传递给我,然后将该值传递给模型,然后它将其用于计算max_speed_on_track
并返回该值。
Obviously if no track is provided by the user then I don't want to return max_speed_on_track
in the json. 显然,如果用户未提供任何曲目,那么我不想在json中返回max_speed_on_track
。
The controller method is very basic for now (I still need to add the code that checks for the track param). 目前,控制器方法非常基础(我仍然需要添加检查轨道参数的代码)。 The code throws the error on the save line. 该代码在保存行上引发错误。
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
Try this out: 试试看:
class Car < ApplicationRecord
attr_accessor :max_speed_on_track
attr_accessor :track
def as_json(options = {})
if track.present?
options.merge!(include: [:max_speed_on_track])
end
super(options)
end
end
Since Rails uses the attributes
method, and you're only needing this for json output, you can override the as_json
method just like in this article . 由于Rails使用attributes
方法,并且只需要此attributes
用于json输出,因此可以像本文一样覆盖as_json
方法。 This will allow you to include your max_speed_on_track
method in your json output when the track
is present (not nil). 当track
存在时(而不是nil),这将允许您将max_speed_on_track
方法包括在json输出中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.