2012-07-08 56 views
0

我想要的: 我可以上传文件并将其分配给对象(例如Person)的站点。 对于上传,我使用的是carrierwave。我想要有两个分开的模型:“人物”和“附件”。每个人只有一个附件。 在我看来,我想设置上传到一个嵌套的形式,'field_for'。未知的属性_id与嵌套的模型和表格

我的代码

#app/models/person.rb 
has_one :attachment 
accepts_nested_attributes_for :attachment 
attr_accessible :name, :attachment_attributes 

#app/models/attachment.rb 
attr_accessible :description, :file 
belongs_to :person 
mount_uploader :file, AttachmentUploader 

#app/controllers/person_controller.rb 
def new 
    @person = Person.new 
    @person.build_attachment 
end 

#app/views/person/new.html.haml 
= form_for @person, :html => {:multipart => true} do |f| 
    = f.fields_for :attachment do |attachment_form| 
    attachment_form.file_field :file 
    = f.submit 

我的问题: 当我试图打开new.html我收到此错误: 未知属性:PERSON_ID

我有不知道为什么会出现此错误。 有人有想法吗?

(我用的导轨3.2.6与1.8.7红宝石)

+0

附件表中是否有'person_id'列? – davidb 2012-07-09 14:12:33

+0

@davidb附件表中没有'person_id'列。不应该'belongs_to:person'创造这个? – Sebastian 2012-07-11 12:08:14

回答

2

当建立两个模型之间的关系总是有两个步骤。

1.)创建需要的列/表。

当您有1..n或1..1的关系时,需要在其中一个表中有一个关联列。这些列不是自动创建的。你需要创建它们。对于这个fiorst创建迁移:

rails g migration addColumnToTable 

这会在你需要编辑db/migrate/迁移文件。在up方法中添加add_colun命令添加一列

add_column :tablename, :column_name, :column_type 

你会发现整个文档在这里:http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

然后,你需要通过执行rake db:migrate

2.运行迁移)添加(这是你已经做的!)

这应该为你做,...

0

只需在您的附件表中添加一个person_id列即可。这是外键轨道正在寻找。