在friendly_id 中的slug_candidates 中使用关联的字段名称 [英] using an associated field name in slug_candidates in friendly_id

查看:36
本文介绍了在friendly_id 中的slug_candidates 中使用关联的字段名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在我的 slug_candidates 方法中使用关联?

Is it possible to use a association in my slug_candidates method?

例如,我的模型所属的位置_to :car

for example, where my model belongs_to :car

def slug_candidates
    [
      [car.owner, :horsepower, "horsepower"],
      [car.owner, car.nickname, :horsepower, "horsepower"]
    ]
end

现在它回来了

NoMethodError: nil:NilClass 的未定义方法`owner'

推荐答案

我假设这是在 ActiveRecord 模型中定义的方法.

这是因为您使用的记录之一没有 car(即 nil).

It's because one of the records you are using does not have a car (ie. it is nil).

因此,当您对该特定记录执行 car.owner 时(顺便说一句,可能有多个)实际上是在尝试在 nil 上调用方法 owner(即nil.owner),因此错误.

So when you do car.owner on that specific record (there may be more than one btw) are essentially trying to call the method owner on nil (ie. nil.owner), therefore the error.

这篇关于在friendly_id 中的slug_candidates 中使用关联的字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆