rails ams,nil:NilClass的嵌套模型未定义方法'
我有以下型号:
class Appeal < ActiveRecord::Base
belongs_to :applicant, :autosave => true
belongs_to :appealer, :autosave => true
end
class Appealer < ActiveRecord::Base
has_many :appeals, :autosave => true
end
class Applicant < ActiveRecord::Base
has_many :appeals
end
我想要的是每个上诉人都对他的最后上诉的申请人提起参考文件
What I want is for every appealer to hold a reference to the applicant of his last appeal
所以我将Appealer模型修改为:
so I modified Appealer model to:
class Appealer < ActiveRecord::Base
has_many :appeals, :autosave => true
def last_applicant
return self.appeals.last.applicant
end
end
但是我得到了错误:
undefined method `applicant' for nil:NilClass
奇怪的是,如果我调试它(通过RubyMine-评估表达式),我可以找到申请人.
what is strange that if I debug this (via RubyMine - Evaluate Expression) I can get the applicant.
如果我想上诉到最后,
class Appealer < ActiveRecord::Base
has_many :appeals, :autosave => true
def last_appeal
return self.appeals.last
end
end
一切正常.
我正在使用active-model-serializer,尝试在序列化器中也这样做(我实际上在特定的调用中需要此值-并非遍及整个模型),但是它也没有出现相同的错误.
Im working with active-model-serializer, tried to do it also in the serializer (I actually need this value on a specific call - not allover the model) but it also didnt worked with the same errors.
AMS代码:
class AppealerTableSerializer < ActiveModel::Serializer
attributes :id, :appealer_id, :first_name, :last_name, :city
has_many :appeals, serializer: AppealMiniSerializer
def city
object.appeals.last.appealer.city
end
end
我的问题: 如何在JSON中获取嵌套对象属性? 我在做什么错了?
MY QUESTION: How can I get the nested object attributes in my JSON? What am I doing wrong?
我的控制器呼叫:
class AppealersController < ApplicationController
def index
appealers = Appealer.all
render json: appealers, each_serializer: AppealerTableSerializer, include: 'appeal,applicant'
end
end
无论是否有包含,我都尝试过,仍然无法正常工作
I've tried with and without the include, still not works
也许我遗漏了一些东西,因为这看起来像您具有上诉人"记录,但还没有任何上诉.
Maybe I am missing something, because this looks like you have Appealer record that doesn't have any appeals yet.
在这种情况下,此代码
def last_appeal
return self.appeals.last
end
将返回nil,这不会引发任何错误.但是如果你叫这个
Will return nil, which won't raise any errors. But if you call this
def last_applicant
return self.appeals.last.applicant
end
return self.appeals.last
为nil,您尝试在nil对象而不是Appeal对象上调用applicant
方法.
return self.appeals.last
is nil and you try to call applicant
method on nil object instead of Appeal object.
要修复此问题,只需添加nil检查即可
To fix it just add check for nil
class Appealer < ActiveRecord::Base
has_many :appeals, :autosave => true
def last_applicant
last = self.appeals.last
if last.nil?
return nil
else
return last.applicant
end
end
end