我正在对我的rails api。 它有一个模型位置。现在,城市可以有多个名字。像“班加罗尔”(父对象)和“班加罗尔”(儿童对象)。模型是自引用的。我想添加一个约束来阻止我的用户引用子对象。他们应该始终引用父对象。自引用父对象如果它有子对象
这里是我的代码:
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
我怎样才能做到这一点? 感谢提前:)
你可以举一个例子,用户会引用一个子对象吗? – RSB
没有。用户总是需要引用父对象。就像用户引用Bangalore(子对象)一样,必须提供约束以便用户引用“bangaluru”(父对象) – Abhishek