Vote count:
0
I have two models
Address.rb
belongs_to :zip
accepts_nested_attributes_for :zip
Zip.rb
has_many :addresses
on the form for a new Address I also create a Zip. But i want to check if the inserted Zip already exists. If it does it should return the existing Zip, if it doesn't it should create a new one
AddressController
def new
@address = Address.new
@address.build_zip
end
I saw on StackOverFlow a similar question without the answer I was hopping for... Someone suggested:
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
what should be at # in order to associate the existing Zip to the Address instead creating a new one?
asked 36 secs ago
RoR - check if record exist before build
Aucun commentaire:
Enregistrer un commentaire