2014-09-03 80 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