2016-05-17 108 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

相關問題