【问题标题】:self referencing to parent object if it has child object如果有子对象,则自引用父对象
【发布时间】:2016-05-17 07:01:20
【问题描述】:

我正在开发我的 rails api。 它有一个模型位置。现在,城市可以有多个名称。像“Bangalore”(父对象)和“Bangaluru”(子对象)。模型是自引用的。我想添加一个约束来防止我的用户引用子对象。它们应该始终引用父对象。

这是我的代码:

class Location < ActiveRecord::Base
  belongs_to :location # i.e. may have a parent location
  has_many :users,  dependent: :restrict_with_error
  validates :name, presence: true, uniqueness: true

  before_save :lowercase_name
  auto_strip_attributes :name, squish: true, nullify: false

  enum status: [
       :invisible, # default
       :major, # a major city
       :minor, # a minor city
       :child, # i.e. it has a parent that should be used instead
   ]
end

我怎样才能做到这一点? 在此先感谢:)

【问题讨论】:

  • 你能举一个用户引用子对象的例子吗?
  • 没有。用户总是必须引用父对象。就像用户引用班加罗尔(子对象)一样,必须提供约束,以便用户引用“bangaluru”(父对象)

标签: ruby-on-rails self-reference


【解决方案1】:

我假设你的locations 表中有一个parent_id 字段,你可以这样做

belongs_to :parent_location, class_name: 'Location', foreign_key: 'parent_id'

现在,user.location.parent_location 将为您提供父位置,或者您可以这样做

location = user.location
location = location.parent_location_present? ? location.parent_location : location

在定位模型中,

def parent_location_present?
  parent_location.present?
end

希望这会有所帮助!

【讨论】:

  • 其实我没有 parent_id 。位置是对自身的自我引用。它具有如上所示的枚举。我只需要编写一个自定义验证器。 def child_location_not_present 如果 location.child.present 返回 false?结尾。但它不工作。如何检查子对象是否存在?
  • 如何获得 location.child?你需要有一个父 id 列来实现这个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-30
  • 2014-11-24
相关资源
最近更新 更多