【问题标题】:Rails 5: attr_accessor throwing NoMethodError (undefined method `keys' for nil:NilClass):Rails 5:attr_accessor 抛出 NoMethodError(nil:NilClass 的未定义方法“键”):
【发布时间】: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


【解决方案1】:

试试这个:

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,您可以像在 this article 中一样覆盖 as_json 方法。当track 存在(非零)时,这将允许您在 json 输出中包含您的 max_speed_on_track 方法。

【讨论】:

  • 谢谢,这行得通……但现在我开始看到这里的限制,我想应该转向 RABL 模板或 ActiveModelSeraliazers。
猜你喜欢
  • 2015-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-14
  • 2013-01-14
  • 2017-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多