我在has_many association
和user
之间有contact_information
。我向contact_information
添加了两列作为address_one
和address_two
。然后将关联更改为用户和contact_information之间的has_one
关联。但我得到的错误是:undefined method
empty?'对于#`
在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
empty?对于#`
我在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