我有一个has_many的问题,我不明白我在哪里错了,在这里搜索并没有给我一个答案呢。rails has_many给'未定义的方法'/销毁不会删除外键
我正在写一个litte应用程序来管理派对。因此,一个对人民帮助在党
class Person < ActiveRecord::Base
has_many :sections
end
的一个模型部分来管理不同的地方的模型的人(一个shotbar,一个地方获得食品等)
class Section < ActiveRecord::Base
belongs_to :person
has_many :shifts
end
的路由用我只是(他们的工作)
resources :people
resources :sections
我的迁移情况如下
class CreatePeople < ActiveRecord::Migration
def change
create_table :people do |t|
t.string :vname
t.string :nname
t.string :mail
t.timestamps
end
end
end
和
class CreateSections < ActiveRecord::Migration
def change
create_table :sections do |t|
t.string :name
t.text :text
t.integer :person_id
t.timestamps
end
end
end
我的问题是:我所理解的has_many我现在应该能够使用
@stuff=Person.sections
获得其中某个人工作的所有部分。
然而,这给了我“未定义的方法`部分'为#”。当我摧毁了一个人并且部分对象中的外键仍然存在时,实际上发生了问题,而我认为rails会将它们设置为NULL,例如,
@person=Person.find(8)
@person.destroy
结束了某处
couldn't find person with id=8
同时取得部
def show
@section=Section.find(params[:id])
if @section.person_id
@person=Person.find(@section.person_id)
end
end
的表演动作,我不知道该怎么做,或者如果我错过了一些迁移。 Rails似乎并没有承认这一对多关系。我已经检查过文档和东西,但找不到差异。也许你可以帮忙。
非常感谢,斯文
'sections'方法是'Person'实例,而不是类定义的。 – 2014-08-28 12:04:02
谢谢!那解决了第一个问题......但是为什么在我摧毁某个人之后仍然存在外键?我希望的是,当我从系统中删除一个人的每个部分person_id,这个人在哪里工作,被设置为NULL – Sven 2014-08-28 12:12:32