Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveModel::MissingAttributeError: can't write unknown attribute `ad_id' with FactoryGirl

I have the following models:

class Ad < ActiveRecord::Base
  belongs_to :page

  has_one :image
  has_one :logo
end

class Page < ActiveRecord::Base
  has_many :logos
  has_many :images
  has_many :ads
end

class Image < ActiveRecord::Base
  belongs_to :page
  has_many :ads
end

And I have defined the following Factories:

factory :page do
  url 'test.com'
end

factory :image do
  width 200
  height 200
  page
end

factory :ad do
  background 'rgb(255,0,0)'
  page
  image
end

When I try to do this:

ad = FactoryGirl.create(:ad) I get the following error ActiveModel::MissingAttributeError: can't write unknown attribute ad_id' right in the line where I decide the image association in the ad Factory.

What am I doing wrong here?

like image 643
Hommer Smith Avatar asked Nov 30 '13 02:11

Hommer Smith


3 Answers

When you say:

has_one :image

Rails expects you to define an ad_id field at the images table. Given the way your associations are organised, I assume you have an image_id and a logo_id a the ads table so instead of:

class Ad < ActiveRecord::Base
  belongs_to :page

  has_one :image
  has_one :logo
end

You probably mean:

class Ad < ActiveRecord::Base
  belongs_to :page
  belongs_to :image
  belongs_to :logo
end

If that's not the case then you need to add ad_id columns to both Image and Logo.

like image 98
Maurício Linhares Avatar answered Nov 01 '22 00:11

Maurício Linhares


I ran into this same error and it took a while to figure out a fix. Just in case this helps someone else in the future, here's my scenario and what worked for me. Class names have been changed as this is for work:

I had 2 namespaced models:

Pantry::Jar
has_many :snacks, class_name: Pantry::Snack
accepts_nested_attributes_for :snacks

Pantry::Snack
belongs_to :pantry_jar, class_name: Pantry::Jar

When I would create a new jar with new snacks, I would get:

ActiveModel::MissingAttributeError: can't write unknown attribute `jar_id'

The fix was to change the has_many to be more explicit about the foreign key:

has_many :snacks, class_name: Pantry::Snack, foreign_key: :pantry_jar_id
like image 36
evan Avatar answered Oct 31 '22 22:10

evan


If you are getting this error while running the specs, it may be the newly added field that are not migrated in the test environment. So migrate it in the test environment with the below command

rake db:migrate db:test:prepare
like image 6
Shamsul Haque Avatar answered Oct 31 '22 23:10

Shamsul Haque