Home Rails updating foreign key for a has_one relationship to nil
Reply: 0

Rails updating foreign key for a has_one relationship to nil

user1369 Published in April 26, 2018, 5:30 pm

I have an Anexo model with has_one relationship with an Attachment model

class Anexo < ApplicationRecord
  validates :descricao, presence: true, uniqueness: true
  has_one :attachment,  dependent: :restrict_with_error, validate: true

class Attachment < ApplicationRecord
  validates :nome, :tamanho, :anexo, presence: true
  belongs_to :anexo 

In my AnexosController,

def update
   respond_to do |format|
     if @anexo.update(anexo_params)
        format.html { redirect_to @anexo, notice: 'Anexo was successfully updated.' }
        format.json { render :show, status: :ok, location: @anexo }
       format.html { render :edit }
       format.json { render json: @anexo.errors, status: :unprocessable_entity }

When I am creating a new record everythig is working fine and a proper error message is displayed when I left the atachment blank.

When I edit this registry, and do not select any attachment, it displays the message, but the foreign key is set to nil.

If I cancel the operation and come back, the record has been updated and the anexo no longer has the old attachment.

Would you like to know if you can prevent this update from happening in build_attachment?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.314383 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO