Search code examples
ruby-on-railsrubybelongs-to

Rails belongs_to relationship not working


Currently I am having issues with the belongs_to relationship between my Page model and my Companies model.

I receive the following error message when I am on the Page show.erb.html and I am accessing @page.company.id: undefined method `id' for nil:NilClass

This error message with and without the attr_accessor method in the companies model.

Page Model:

class Page < ActiveRecord::Base
  belongs_to :company
end

Company Model:

class Company < ActiveRecord::Base
    attr_accessor :id, :name
    has_many :pages

end

Companies Migration:

class CreateCompanies < ActiveRecord::Migration
  def change
    create_table :companies do |t|
      t.string :name

      t.timestamps
    end
  end
end

Pages migration:

class CreatePages < ActiveRecord::Migration
  def change
    create_table :pages do |t|
      t.string :name
      t.references :companies, index: true

      t.timestamps
    end
  end
end

Solution

  • As a page has a single company, your page migration should use:

    t.references :company, index: true
    

    (singular) instead of :companies (plural). This should allow rails to populate it properly.