我有一个模型caleld SpacialBody,我需要播种一些记录,所以首先我把它添加到我的种子.rb
[
["Sol",0,0,0,"standard"]
].each do |body|
nb=SpacialBody.find_or_create_by_name(body[0])
nb.name = body[0]
nb.x = body[1]
nb.y = body[2]
nb.type = SpacialBody::Types[body[3]]
nb.class = body[4]
nb.save
end
这会产生错误。然后我进入控制台测试代码,发现发生了这种情况:
SpacialBody.new => # SpacialBody.find_by_name( “太阳”) =>零 SpacialBody.find_or_create_by_name( “太阳”) NoMethodError:未定义的方法
generated_methods' for nil:NilClass from /var/lib/gems/1.8/gems/activesupport-2.3.8/lib/active_support/whiny_nil.rb:52:in
method_missing' 来自/var/lib/gems/1.8/gems/activerecord-2.3.8/lib/active_record/attribute_methods.rb:356:inrespond_to?' from /var/lib/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:2906:in
assign_attributes' 来自/var/lib/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:2902:ineach' from /var/lib/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:2902:in
assign_attributes' 来自/var/lib/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:2775:inattributes=' from /var/lib/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:1965:in
发送' 来自/var/lib/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:1965:infind_or_create_by_name' from /var/lib/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:2475:in
initialize' 来自/var/lib/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:1963:innew' from /var/lib/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:1963:in
find_or_create_by_name' 来自/var/lib/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:1975:insend' from /var/lib/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:1975:in
method_missing' 来自(irb):3
我已经在其他项目中使用了find_or_create_by_field而没有重复,我在这里的设置中看不到任何不同。
只有这个模型有问题,同一项目中的其他模型才能正常工作。
答案 0 :(得分:2)
捂脸
使用类和类型作为模型中的字段....不是一个好的举动
这两个都是保留名称,在构建方法时会导致ActiveRecord失败。