我有两个模型的形式为一个新的地址,我也创建一个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关联到地址,而不是创建一个新的?
的可能重复[Rails的ActiveRecord的创建或找到(http://stackoverflow.com/questions/17905038/rails-activerecord-create-or-find ) – 2014-09-03 23:38:32
http://blog.mitchcrowe.com/blog/2012/04/14/10-most-under-used-activerecord-relation-methods/ – 2014-09-03 23:39:44
我不明白这是如何与您指出的重复。正如我在我的问题中所说的,它是另一个[问题]的副本(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