2014-09-03 81 views
0

我有兩個模型的形式爲一個新的地址,我也創建一個Zip上回報率 - 檢查是否存在記錄之前建立

 
Address.rb 
    belongs_to :zip 
    accepts_nested_attributes_for :zip 

Zip.rb 
    has_many :addresses 

。但我想檢查插入的Zip是否已經存在。如果這樣做,應該返回現有的壓縮,如果它不應該創建一個新的

 
AddressController 
    def new 
    @address = Address.new 
    @address.build_zip 
    end 

我在計算器上類似question看到沒有答案,我跳了...有人建議:

 
    before_create :check_zip_exists 

    def check_zip_exists 
    @zip = Zip.find_by_cp1_and_cp2(self.cp1, self.cp2) 
    if @zip!=nil 
     # 
    end 
    end 

什麼應該在#爲了將現有的Zip關聯到地址,而不是創建一個新的?

+0

的可能重複[Rails的ActiveRecord的創建或找到(http://stackoverflow.com/questions/17905038/rails-activerecord-create-or-find ) – 2014-09-03 23:38:32

+0

http://blog.mitchcrowe.com/blog/2012/04/14/10-most-under-used-activerecord-relation-methods/ – 2014-09-03 23:39:44

+0

我不明白這是如何與您指出的重複。正如我在我的問題中所說的,它是另一個[問題]的副本(http://stackoverflow.com/questions/4978893/how-to-check-if-a-record-exists-before-creating-a-new- one-in-rails3)並沒有完整的答案,這就是爲什麼我再次要求 – NunoRibeiro 2014-09-04 09:16:38

回答

2

做到這一點的方法是安排是這樣的:

 
Address.rb 
    belongs_to :zip 
    accepts_nested_attributes_for :zip, :reject_if => :check_zip_exists 

    private 

    def check_zip_exists(attributed) 
    cp1 = attributed['cp1'] 
    cp2 = attributed['cp2'] 
    zip = Zip.where(:cp1=>cp1, :cp2=>cp2).first 
    if zip.nil? 
     return false 
    else 
     self.zip_id = zip.id 
    end 
    end 
2

試着這麼做:

zip = Zip.where(field: value).first_or_create 

更新

當您使用accepts_nested_attributes_for :zip發生了什麼裏面是產生一種叫做zip_attributes=(attributes)公共方法。

這個方法,調用一個私有方法(取決於是否關係是一個集合或單一對象),你的情況被稱爲私有方法是assign_nested_attributes_for_one_to_one_association

所以你可以重寫public_method zip_attributes=(attributes)Address模型來代替正常行爲:

def zip_attributes=(attributes) 
    self.zip = Zip.where(attributes).first_or_create #you can change attributes to be the fields that you need to find the correct zip 
end 

更新2

def zip_attributes=(attributes) 
    cp1 = attributes.delete(:cp1) 
    cp2 = attributes.delete(:cp2) 
    self.zip = Zip.where(cp1: cp1, cp2: cp2).first_or_create(attributes) 
end 
+0

將返回現有的Zip而不是創建一個新的? – NunoRibeiro 2014-09-03 23:47:09

+0

是的,它會返回現有的郵編 – Aguardientico 2014-09-04 00:00:35

+0

,我應該把它放在哪裏? – NunoRibeiro 2014-09-04 00:18:09