错误(私有方法“select”调用了 nil:NilClass):

Error (private method `select' called for nil:NilClass):

为什么我会收到此错误?我该如何解决?

ActionView::Template::Error (private method `select' called for nil:NilClass):

class MyformObject

  include ActiveModel::Model

  #validations


@form_structure =
  [
    {  name: :country, model: :car, field_type: :string },
    {  name: :street, model: :repair_center, field_type: :string }
  ]

  def get_model_from_name(name)
    model = @form_structure.select { |record| record[:name] == name }.first[:model]
  end  

  def type_for_attribute(name)
    get_model_from_name(name).to_s.capitalize.constantize.type_for_attribute
  end 

  def has_attribute?(name)
    get_model_from_name(name).to_s.capitalize.constantize.attributes.key?(name.to_s)
   end

def self.fields_of_model(model)
  form_structure.select { |record| record[:model] == model }.map { |record| record[:name] }
end

 end

更新版本:

ERROR: undefined method `[]' for nil:NilClass def get_model_from_name(name)
model = self.class.form_structure.select { |record| record[:name] == name }.first[:model] end

class MyformObject

  include ActiveModel::Model

  #validations


def self.form_structure 
  [
    {  name: :country, model: :car, field_type: :string },
    {  name: :street, model: :repair_center, field_type: :string }
  ]
end

  def get_model_from_name(name)
    model = self.class.form_structure.select { |record| record[:name] == name }.first[:model]
  end  

  def type_for_attribute(name)
    get_model_from_name(name).to_s.capitalize.constantize.type_for_attribute
  end 

  def has_attribute?(name)
    get_model_from_name(name).to_s.capitalize.constantize.attributes.key?(name.to_s)
   end

def self.fields_of_model(model)
  form_structure.select { |record| record[:model] == model }.map { |record| record[:name] }
end

def self.delegate_fields_to(*models)
      models.each do |model|
        fields_of_model(model).each do |attr|
          delegate attr.to_sym, "#{attr}=".to_sym, to: model
        end
      end
    end

 end

恕我直言,常量是处理该数组的好方法,因为它充满了硬编码值,而且它只包含两个元素。

所以你可以这样做:

class MyformObject
  FORM_STRUCTURE = [
    { name: :country, model: :car, field_type: :string },
    { nname: :street, model: :repair_center, field_type: :string }
  ].freeze
  private_constant :FORM_STRUCTURE

  def get_model_from_name(name)
    FORM_STRUCTURE.select { |record| record[:name] == name }.first[:name]
  end 
end

p MyformObject.new.get_model_from_name(:country)
# [:country]

在那里你可以看到常量不能被修改,只能在 MyformObject 范围内使用。

我删除了模型局部变量赋值,因为它没有被使用。

你可以像这样尝试,这让 little 更容易执行,

  def get_model_from_name(name)
    model = form_structure.select { |record| record[:name] == name }.first[:model]
  end

  def form_structure
    [
      {  name: :country, model: :car, field_type: :string },
      {  name: :street, model: :repair_center, field_type: :string }
    ]
  end

为了更好的封装,您可以将方法 form_structure 放在私有范围内。