如何修复“未定义的方法‘空?’对于#<ContactInformation:0x007fc8be45cc98>:错误?

How to fix "undefined method `empty?' for #<ContactInformation:0x007fc8be45cc98>: error?

我有 has_many associationusercontact_information 之间。我向 contact_information 添加了两列作为 address_oneaddress_two。然后将关联更改为 has_one 用户与 contact_information 之间的关联。但我得到的错误是: undefined method空的? #`

在app/models/concerns/user_associations.rb:

    has_many :contact_informations,
     -> { where(address_one: nil, address_two: nil) },
      as: :user

已更改为

    has_one :contact_information,
     -> { where(address_one: nil, address_two: nil) },
      as: :user

然后在 ContactInformationsController 中,将 contact_informations 更改为 contact_information。我在 ContactInformationsController#show 中遇到错误:

  def show
    if @user.contact_information.empty?
      redirect_to new_contact_information_path
    else
      redirect_to edit_contact_information_path
    end
  end

@user.contact_informations.empty?改为@user.contact_information.empty?。但是当我尝试访问该页面时,

NoMethodError - undefined method空的? #`

我在 INTERNET 上查找类似问题,大多数人都说要转换它 .to_s。但是并没有解决我的问题

contact_information 的对象存在。那为什么它在 .empty? 上出错?有人可以解释一下吗?

谢谢

empty? 方法在可枚举对象上定义,包括活动记录关系,但它没有在单个 ActiveRecord 对象上定义,例如 ContactInformation 实例。如果你想检查关联存在,你可以简单地做:

if @user.contact_information
  redirect_to edit_contact_information_path
else
  redirect_to new_contact_information_path
end