Rails:查找实例的关系名称

时间:2015-03-04 12:24:17

标签: ruby-on-rails activerecord relationship

假设我们有这种关系:

class Company < ActiveRecord::Base
  has_one :company_address, class_name: 'Address', foreign_key: 'company_address_id'
  has_one :overseas_address, class_name: 'Address', foreign_key: 'overseas_address_id'
end

如果我在地址实例中pry,是否可以返回:company_address:overseas_address

字段相同,但我想做不同的验证。

是的,有其他方法可以解决问题,但我更感兴趣的是找到关系的名称是否真的可行。

谢谢!

1 个答案:

答案 0 :(得分:1)

您的地址模型中应该有相应的belongs_to:,然后尝试Address.reflect_on_all_associations(belongs_to) 它将返回ActiveRecord::Reflection::AssociationReflection的集合,该集合将具有不同的name(取决于您的belongs_to)

为了检查实例,您应将belongs_tos标记为inverse_of: :put_corresponding_association,将has_one标记为inverse_of belongs_tos,然后您可以检查相应的方法(由belongs_tos生成)是否存在父公司对象

这个想法是假设一个地址为

class Address < ActiveRecord::Base
  belongs_to :company, class_name: 'Company', foreign_key: 'company_address_id', inverse_of: :company_address
  belongs_to :oversea, class_name: 'Company', foreign_key: 'overseas_address_id', inverse_of: :overseas_address
end

class Company < ActiveRecord::Base
  has_one :company_address, class_name: 'Address', foreign_key: 'company_address_id', inverse_of: :company
  has_one :overseas_address, class_name: 'Address', foreign_key: 'overseas_address_id', inverse_of: :oversea
end

并将地址创建为address = company.overseas_address.new

然后

address.company == nil
address.oversea == company