2014-02-16 14 views
0

我有一個複雜的Rails模型設置,我會盡量簡化。此設置的目標是能夠擁有長期存在的對象(Person,Pet),但它們之間的關係每年都會通過TemporalLink更改。基本上,我有這些模型:Rails不會保存,如果重複

class Person < ActiveRecord::Base 
    include TemporalObj 

    has_many :pet_links, class_name: "PetOwnerLink" 
    has_many :pets, through: :pet_links 
end 

class Pet < ActiveRecord::Base 
    include TemporalObj 

    has_many :owner_links, class_name: "PetOwnerLink" 
    has_many :owners, through: :owner_links 
end 

class PetOwnerLink < ActiveRecord::Base 
    include TemporalLink 

    belongs_to :owner 
    belongs_to :pet 
end 

和這些問題:

module TemporalLink 
    extend ActiveSupport::Concern 

    # Everything that extends TemporalLink must have a `year` attribute. 
end 

module TemporalObj 
    extend ActiveSupport::Concern 

    # Everything that extends TemporalObj must have a find_existing() method. 

    #################### 
    # Here be dragons! # 
    #################### 
end 

期望的行爲是:

  • 當創建一個TemporalObjPetPerson):

    1)檢查是否有現有的,根據一定的條件,與find_existing()。 2)如果找到了現有的副本,請不要執行創建,但仍然對關聯的對象執行必要的創建。 (這似乎是棘手的部分

    3)如果沒有找到重複,執行創建。

    4)現有的魔力已經自動創建必要的TemporalLink對象。]

  • 當摧毀一個TemporalObj

    1)檢查是否在一年以上存在的對象。 (這在實際中比在這個例子中更簡單。)

    2)如果對象僅在一年內存在,則銷燬它並關聯TemporalLink s。

    3)如果物體存在一年以上,只要銷燬其中一個TemporalLink即可。

我的問題是我有很多TemporalObj小號獨特性驗證,所以當我嘗試創建一個新的副本,確認之前,我可以執行任何around_create魔術失敗。任何想法,我怎麼可以爭論這個工作?

回答

0

針對JacobEvelyn的評論,這是我做的。

  1. 創建的自定義驗證像這樣
 
     def maintain_uniqueness 
     matching_thing = Thing.find_by(criteria1: self.criteria1, criteria2: self.criteria2) 
     if !!matching_thing 
      self.created_at = matching_thing.created_at 
      matching_thing.delete 
     end 
     true 
     end 
  • 它添加到我的驗證

    validate :maintain_event_uniqueness

  • 它的工作。

  • +0

    有趣的方法。我不喜歡刪除舊對象的想法(它可能會有其他關聯現在被破壞),但是因爲這適用於我給出的示例,並且比我想出的解決方案簡單得多(這非常複雜重寫默認的Rails方法的舞蹈),我會接受它。 – JacobEvelyn

    2

    你可以(也應該)在這裏使用Rails的內置驗證。你所描述的是validates_uniqueness_of,你可以將其範圍包括多列。

    例如:

    class TeacherSchedule < ActiveRecord::Base 
        validates_uniqueness_of :teacher_id, scope: [:semester_id, :class_id] 
    end 
    

    http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of

    +0

    我正在使用唯一性驗證。問題是,我想在新的一年中創建一個重複的「Person」(在年份是全局概念的情況下),只需將鏈接對象添加到現有的Person中即可。我不希望創建失敗。 – JacobEvelyn