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

后端 未结 4 708
抹茶落季
抹茶落季 2021-01-03 18:06

I have the following models:

class Ad < ActiveRecord::Base
  belongs_to :page

  has_one :image
  has_one :logo
end

class Page < ActiveRecord::Base
           


        
4条回答
  •  离开以前
    2021-01-03 18:40

    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
    

提交回复
热议问题