2016-05-17 106 views
0

我正在对我的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 

我怎样才能做到这一点? 感谢提前:)

+0

你可以举一个例子,用户会引用一个子对象吗? – RSB

+0

没有。用户总是需要引用父对象。就像用户引用Bangalore(子对象)一样,必须提供约束以便用户引用“bangaluru”(父对象) – Abhishek

回答

0

我假设你有你的locationsparent_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 

希望这有助于!

+0

其实我没有parent_id。位置是自我引用的。它具有如上所示的枚举。我只需要编写一个自定义验证器。 def child_location_not_present 如果location.child.present返回false? 结束。但它不工作。如何检查子对象是否存在? – Abhishek

+0

如何获得location.child?你需要有一个父母ID列来实现这一点 – RSB

相关问题