ActiveAdmin 无法识别模型中的 "self"

ActiveAdmin doesn't recognize "self" within a model

例如当我GET/admin/consoles/1/edit时,会发生这种情况:

Couldn't find Brand with 'id'=

然后它突出显示了我在其中的以下代码片段 /app/models/console.rb:

def full_name
  brand = Brand.find(self.brand_id).name
  "#{brand} #{self.name}"
end

它似乎无法识别 self.brand_id。想法?

您可以通过测试是否存在 brand_id 参数来避免错误:

def full_name
  if self.brand_id.present?
     brand = Brand.find(self.brand_id).name
     "#{brand} #{self.name}"
  else
     self.name #or other combination of parameters not using the brand model
  end
end

如果这对您有帮助,请告诉我们。

我需要看看你的 app/models/console.rb 才能确定,但​​你似乎应该有一个 belongs_to 关系,然后你就可以使用那个关系......像这样:

class Console < ActiveRecord::Base
  belongs_to :brand

  def full_name
    "#{brand.name} #{name}"
  end
end

但也许你应该像这样保护它:

  def full_name
    ("#{brand.name} " if brand.present?) << "#{name}"
  end