Search code examples
ruby-on-railsbelongs-torails-activerecord

belongs_to relationship not working


I have following active record class

class Car < ActiveRecord::Base
  belongs_to :owner
end

in the code when I try this

Car.first.owner

it gives me error "undefined method owner"

Can any one plz let me now if I'm missing any thing


Solution

  • You need to write the relation on the Owner side : has_one :car or has_many :cars depending on your needs.

    class Car < ActiveRecord::Base
        belongs_to :owner
    end
    
    class Owner < ActiveRecord::Base
        has_one :car
    end