ruby-on-rails-5associationsfieldassignment-operatorhas-one

Rails and Assigining Association Object


I was actually going through different associations and came up to something which I find a bit odd.

I have an association

class Account < ApplicationRecord
end

class Supplier < ApplicationRecord
  has_one :account
end

migration file

class AddSupplierToAccount < ActiveRecord::Migration[6.0]
  def change
    add_reference :accounts, :supplier, foreign_key: true
  end
end

As I was studying I didn’t make it bidirectional.

I went in to the Rails console and created an account object as well as a supplier object. I then assigned the account object like so:

supplier.account = account

but without saving the supplier object the transaction got commited to the database at the time of assignment. Should this be the way or am I doing anything wrong? If this is the way why?


Solution

  • Add belongs_to :supplier under Account then review this page as to why you should: https://guides.rubyonrails.org/association_basics.html

    Really important as a rails developer to read the entire Rails Guide for the version of rails you are using, tons of useful information there and probably 80% of the common rails issues can be solved by the information it contains.