Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails 5:attr_访问器抛出NoMethodError(nil:NilClass的未定义方法'keys'):_Ruby On Rails_Json_Attr - Fatal编程技术网

Ruby on rails Rails 5:attr_访问器抛出NoMethodError(nil:NilClass的未定义方法'keys'):

Ruby on rails Rails 5:attr_访问器抛出NoMethodError(nil:NilClass的未定义方法'keys'):,ruby-on-rails,json,attr,Ruby On Rails,Json,Attr,我的模型中有两个非数据库属性。如果其中一个有值,我需要在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)

我的模型中有两个非数据库属性。如果其中一个有值,我需要在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
试试这个:

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

由于Rails使用attributes方法,而您只需要将其用于json输出,因此可以像中一样重写as_json方法。这将允许您在轨迹不为零的情况下,在json输出中包含max_speed_on_track方法。

如果这仅适用于调用_json时,为什么不重写as_json方法而不是attributes方法?还有,不要做if!self.track.nil?,可以使用if track.present?。它读起来更容易。谢谢,但是如果self.track.present?抛出与我读到的关于_json相同的错误,但我仍然被卡住了。我应该在as_json方法中添加什么,以便在track不为null时包含我想要的字段,但在track有值时将其排除。谢谢,这是可行的……但现在我开始看到这里的限制,我想应该转到RABL模板或ActiveModelSerializer。
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