Search code examples
ruby-on-railsrubyruby-on-rails-4overridingbelongs-to

Overriding object in belongs_to relation


I have such models:

class User
  belongs_to :authenticity
end

class Authenticity
  has_one :user
end

now I create authenticity for user:

u = User.first; u.authenticity = Authenticity.create

and now I assign new authenticity:

u.authenticity = Authenticity.create

now I have in my database two authenticities:

irb(main):035:0> Authenticity.all
  Authenticity Load (0.3ms)  SELECT "authenticities".* FROM "authenticities"
=> #<ActiveRecord::Relation [
     #<Authenticity id: 22, token: nil, created_at: "2015-09-15 08:18:09", updated_at: "2015-09-15 08:18:46", user_id: nil>, 
     #<Authenticity id: 23, token: nil, created_at: "2015-09-15 08:18:45", updated_at: "2015-09-15 08:18:46", user_id: "1">
   ]>

One which belongs to user and one without any user (user_id: nil). What I want is to create new authenticity and do not store authenticities with nils in user_id field. I'm currently destroying the old one manually, but I'm curious if I can say somehow rails to do it for me. I don't want to use after_create however. Is there some solution for this?


Solution

  • You are seeing two records because you are creating them twice, do this instead

    u = User.first 
    u.create_authenticity
    

    You can enforce a check before creating an Authenticity record

    u.authenticity ||= Authenticity.create
    

    If you want to delete the old Authenticity record with the new one then do this

    if u.authenticity
      u.authenticity.destroy
      u.authenticity = Authenticity.create
    end