【发布时间】: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