Ruby-on-rails ActiveModel::MissingAttributeError: 无法使用 FactoryGirl 写入未知属性“ad_id”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20295710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ActiveModel::MissingAttributeError: can't write unknown attribute `ad_id' with FactoryGirl
提问by Hommer Smith
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.
ad = FactoryGirl.create(:ad) 我ActiveModel::MissingAttributeError: can't write unknown attribute ad_id'在决定广告工厂中的图像关联的行中得到以下错误。
What am I doing wrong here?
我在这里做错了什么?
回答by Maurício Linhares
When you say:
当你说:
has_one :image
Rails expects you to define an ad_idfield at the imagestable. Given the way your associations are organised, I assume you have an image_idand a logo_ida the adstable so instead of:
Rails 期望您ad_id在images表中定义一个字段。鉴于你的协会的组织方式,我假设你有一个image_id和logo_id一对ads表,而不是:
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_idcolumns to both Imageand Logo.
如果不是这种情况,那么您需要将ad_id列添加到Image和Logo。
回答by evan
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:
我有 2 个命名空间模型:
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_manyto be more explicit about the foreign key:
解决方法是has_many将外键更改为更明确:
has_many :snacks, class_name: Pantry::Snack, foreign_key: :pantry_jar_id

